实体框架在运行时将模型类映射到表 [英] Entity Framework map model class to table at run time

查看:60
本文介绍了实体框架在运行时将模型类映射到表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用ASP.NET Core 2.0和Entity Framework的项目中,我试图将已知的表架构(编码为类 MyTableClass )映射到未知的表名.该表名由用户在运行时指定,因此可以在Context类的 OnModelCreating 方法之外进行.有没有办法做下面的伪代码:

In a project using ASP.NET Core 2.0 and Entity Framework, I'm trying to map a known table schema (coded into class MyTableClass) to an unknown table name. This table name is given by the user at run time, so this is done outside of the OnModelCreating method of the Context class. Is there a way to do something like the following pseudocode:

void OnUserEnteredTableNameFromUI(string tableName)
{
    var modelBuilder = new ModelBuilder(???);  // how?
    modelBuilder.Entity<MyTableClass>().ToTable(tableName);
    // how to get a ref to DbSet<MyTableClass> myTable from here?
}

推荐答案

我见过这样的情况,其中具有相同结构但表名不同的数据库已部署到多个站点.在这种情况下,EF仅需要在应用程序启动时知道表名.

I've seen situations where databases with identical structure but varying table names had been deployed to several sites. In that case, EF only needs the know the table name(s) at application startup.

这可以通过向上下文添加构造函数参数来完成:

This can be done by adding a constructor parameter to the context:

private readonly string _userDefinedTableName;

public MyContext(string userDefinedTableName)
{
    _userDefinedTableName = userDefinedTableName;
}

然后,在 OnModelCreating 中:

modelBuilder.Entity<MyTableClass>().ToTable(_userDefinedTableName);

但是,在您的情况下,名称必须在运行时更改任何次数.使用实体框架,这是不可能的(确切地说,太不切实际了,无法进行实际考虑).EF对每个上下文类仅一次编译并存储模型,因为对于每个上下文实例进行所有操作都太昂贵了.

However, in your case the name has to change any number of times at runtime. With Entity Framework, that's impossible (well, more exactly, too impractical to really contemplate it). EF compiles and stores model once per context class, because it would be too expensive to do all that for each context instantiation.

这意味着 OnModelCreating 在应用程序中运行不超过一次,并且第一个表名保留了.

That means that OnModelCreating runs not more than once in an application and the first table name remains.

您将必须找到其他方法来动态处理表数据,或更改设计,以便将多个表转换为一个固定表.

You'll have to find other ways to address table data dynamically, or change the design so the multiple tables can be converted into one fixed table.

这篇关于实体框架在运行时将模型类映射到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆