动态更改Fluent API映射 [英] Change Fluent API mapping dynamically
问题描述
我们的项目首先使用Entity Framework Code.我们希望有一个实例,其中一个非常简单的POCO代表数据库中的许多表.它是SQL Azure中水平分区策略的一部分. SQL Azure不支持文件组,因此它不支持典型的分区.将有大量的表,因此通过基本表上的CHECK CONSTRAINT使用UNION ALL视图作为分区视图是不可行的.
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");
.我们可以在工厂内执行此映射吗?我们希望将元数据提供给工厂,然后让它使用Fluent API,而不是通过ModelBuilder在POCO和表之间进行一对一映射.
. 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.
推荐答案
您可以向DbContext
派生类中添加一个构造函数,该构造函数具有两个用于表名和元模式名的字符串参数.您可以将名称存储在成员变量中,并在ToTable
方法中使用它们.
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.
DbModel
是在实际需要时创建的,因此构造函数始终在OnModelCreating
事件之前运行. (在派生类中并非总是如此,但这是一个不同的主题.)
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 DbModel
s and build DbContext
s by the constructor accepting a DbCompiledModel
.
这篇关于动态更改Fluent API映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!