【问题标题】:Dynamically Instantiate Model object in Entity Framework DB first by passing type as parameter首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象
【发布时间】:2017-10-23 21:02:40
【问题描述】:

需要通过将表名作为参数传递来动态创建实体框架生成模型类的实例(在 DB 优先方法中生成模型并使用 EF 6.0)

喜欢,

// Input Param
string tableName 

// Context always same
DBContext dbContext= new DBContext(); 

//Need to create object query dynamically by passing 
//table name from front end as below  

 IQueryable<"tableName"> query = dbContext."tableName ";

需要传递 100+ 表作为输入参数,所有表的结构都相同。

请帮忙。

【问题讨论】:

    标签: c# asp.net entity-framework linq entity-framework-6


    【解决方案1】:

    您可以使用Dictionary。也许你想要这样的东西:

    // Input Param
    string tableName = "TblStudents";
    Dictionary<string, Type> myDictionary = new Dictionary<string, Type>()
    {
        { "TblStudents", typeof(TblStudent) },
        { "TblTeachers", typeof(TblTeacher) }
    };
    
    // Context always same
    DBContext dbContext = new DBContext();
    DbSet dbSet = dbContext.Set(myDictionary[tableName]);
    

    但是您不能使用任何 LINQ 扩展方法,因为它们是在泛型类型 IQueryable&lt;T&gt; 上定义的,但 DbContext.Set 的非泛型重载会返回非泛型 DbSet。这个类也实现了非通用IQueryable。 您有两种选择在这里使用 LINQ 方法:

    1. System.Linq.Dynamic 添加到您的项目中(要安装System.Linq.Dynamic,请在包管理器控制台中运行以下命令):

      安装包 System.Linq.Dynamic

      然后你可以:

      var dbSet = dbContext.Set(myDictionary[tableName]).Where("Id = @a", 12);
      
    2. 使用Find 方法:

      //But this returns a single instance of your type
      var dbSet = dbContext.Set(myDictionary[tableName]).Find(12);
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      相关资源
      最近更新 更多