使用实体框架按名称获取表 [英] Get table by name with Entity Framework
问题描述
我有这段代码,一切正常.
I've this code and everything works just fine.
using (var db = new ApplicationDbContext())
{
md = db.Modles.ToList();
}
我的问题是我有一个名为 M
的参数,这是我创建的模型的名称,因此它可以是动态的.
My question is that I have a parameter called M
and that is the name of a Model I've created, so it can be dynamic.
有没有办法做这样的事情:
Is there a way to do something like this:
var M = "Modles"; // or M = "Modles2"
using (var db = new ApplicationDbContext())
{
md = db[M].ToList();
}
我尝试了实体框架按名称获取表和
I've tried Entity Framework Get Table By Name and Entity Framework get table by variable name but without any luck. Can this be done?
推荐答案
您提供的第二个链接上的解决方案实际上不起作用,因为它缺少一个简单的步骤:上的方法
是一种通用方法,因此在编译时或至少在运行时,您不能简单地调用它而不告知类型.由于您希望动态调用它,因此可以选择运行时解析.以下示例应该起作用: Set
DbContext
The solution on second link you provided actually doesn't work because it's missing a simple step: The method Set
on DbContext
is a generic method, so you cannot simply invoke it without telling the type, either at compile time or at least at runtime. Since you want it to be called dynamically, runtime resolution is the option you're left with. The following example should work:
var entityNs = "myentities";
var table = "Model";
var entityType = Type.GetType($"{entityNs}.{table}");
var methodInfo = typeof(ApplicationDbContext).GetMethod("Set");
var generic = methodInfo.MakeGenericMethod(entityType);
dynamic dbSet = generic.Invoke(myContext, null);
var list = dbSet.GetList();
这篇关于使用实体框架按名称获取表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!