使用实体框架按名称获取表 [英] Get table by name with Entity Framework

查看:59
本文介绍了使用实体框架按名称获取表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,一切正常.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆