问题描述
需要通过将表名作为参数传递来动态创建实体框架生成模型类的实例(在 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:
添加
System.Linq.Dynamic
到您的项目中(要安装System.Linq.Dynamic
,请在 Package Manager Console 中运行以下命令):
Add
System.Linq.Dynamic
to your project (to installSystem.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);
这篇关于首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!