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);
这篇关于首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
