首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象

Dynamically Instantiate Model object in Entity Framework DB first by passing type as parameter(首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象)
本文介绍了首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Have a requirement to create instance of Entity Framework generated Model class dynamically by passing table name as parameter (Model generated in DB first approach and using 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+ 表作为输入参数,所有表的结构都相同.

Need to pass 100+ tables as input param and structure of all table is same.

请帮忙.

推荐答案

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

You can use a Dictionary. Maybe you want something like this:

// 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 上定义的,但是 DbContext.Set 的非泛型重载, 返回一个非泛型 DbSet.这个类也实现了非通用的IQueryable.您有两种选择在这里使用 LINQ 方法:

But you can not use none of the LINQ extension methods because they are defined on the generic type IQueryable<T> but the non-generic overload of DbContext.Set, returns a non-generic DbSet. Also this class implements non generic IQueryable. You have two option to use LINQ methods here:

  1. 添加 System.Linq.Dynamic 到您的项目中(要安装 System.Linq.Dynamic,请在 Package Manager Console 中运行以下命令):

  1. Add System.Linq.Dynamic to your project (to install System.Linq.Dynamic, run the following command in the Package Manager Console ):

安装包 System.Linq.Dynamic

Install-Package System.Linq.Dynamic

然后你可以:

var dbSet = dbContext.Set(myDictionary[tableName]).Where("Id = @a", 12);

  • 使用查找方法:

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

  • 这篇关于首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

    本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

    相关文档推荐

    DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
    Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
    Programmatically show the desktop(以编程方式显示桌面)
    c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
    InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
    LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)