我首先使用实体框架代码来处理我的数据库。我有几个名称不同但结构相同的表,并且这些表动态出现在数据库中。如何在运行时将 EntityFramework 映射到其中一个表并使用来自 DbContext 实体的数据?
我为使其发挥作用所做的工作:
例如,我的类描述动态创建表的结构是SetElement。
这是我的背景:
public class DataContext : DbContext
{
public DataContext()
: base("RepositoryConnectionString") { }
string setElementsTableId; // the name of table that need to be dynamicly mapped to
// Enforce model recreating
public DataContext(string setElementsTableId)
: this()
{
this.setElementsTableId = setElementsTableId;
}
/* some other entities */
public DbSet<Entities.SetElement> SetElements { get; set; } // dynamicly mapped entity
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
/* come configurations */
if (!string.IsNullOrEmpty(setElementsTableId))
{
modelBuilder.Entity<Entities.SetElement>().Map(x …Run Code Online (Sandbox Code Playgroud)