Change Fluent API mapping dynamically

巧了我就是萌 提交于 2019-11-28 05:02:28

问题


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:


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.



来源:https://stackoverflow.com/questions/9762808/change-fluent-api-mapping-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!