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);
这篇关于首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:首先通过将类型作为参数传递来动态实例化实体框架数据库中的模型对象
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
