Change Fluent API mapping dynamically

2020-02-12 18:18发布

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.

1条回答
▲ chillily
2楼-- · 2020-02-12 18:38

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 the ToTable method.

The DbModel is created when it is actually needed, so the constructor always runs before the OnModelCreating event. (This is not always the case in derived classes, but that's a different topic).

As an optimization you can cache compiled DbModels and build DbContexts by the constructor accepting a DbCompiledModel.

查看更多
登录 后发表回答