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:
添加
System.Linq.Dynamic到您的项目中(要安装System.Linq.Dynamic,请在 Package Manager Console 中运行以下命令):
Add
System.Linq.Dynamicto 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);
这篇关于首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象
基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
