Our project uses Entity Framework Code First. We wish to have an instance where a very simple POCO represents many tables in the database. It is part of a horizontal partitioning strategy in SQL Azure. SQL Azure does not support file groups, thus it does not support typical partitioning. There are going to be a very large numbers of tables, so using a UNION ALL view as a partitioned view via CHECK CONSTRAINTs on the base tables will not be feasible.
Thus, we would prefer to peform the mapping as needed at runtime. However, this occurs in the OnModelCreating event of the DbContext class via code such as
modelBuilder.Entity<EntityName>().ToTable("foo", "bar");
. Is it possible for us to perform this mapping inside a factory? We would prefer to supply metadata to the factory and have it use the Fluent API then, rather than have a one-to-one mapping between POCO and table via the ModelBuilder.
You can add a constructor to your
DbContext
derivative, having two string arguments for table name and metaschema name. You can store the names in member variables and use them in theToTable
method.The
DbModel
is created when it is actually needed, so the constructor always runs before theOnModelCreating
event. (This is not always the case in derived classes, but that's a different topic).As an optimization you can cache compiled
DbModel
s and buildDbContext
s by the constructor accepting aDbCompiledModel
.