Entity Framework linq 中的动态表名 [英] Dynamic table names in Entity Framework linq
问题描述
我正在使用 Entity Framework 6 和 ASP.Net MVC 5.当使用数据库上下文对象时,有没有办法使用变量作为表名,而无需手动编写查询?
I'm using Entity Framework 6 with ASP.Net MVC 5. When using a database context object, is there a way to use a variable for the table name, without having to manually write the query?
例如:
var tableName = "NameOfTable";
result = context.tableName.Find(...);
我知道特定代码不起作用,因为 tableName 没有在上下文中定义,但是有没有办法达到预期的效果?
I know that particular code won't work, because tableName is not defined in context, but is there a way to achieve the desired effect?
这个网站上有一些类似的问题,但他们从来没有真正解决过这个问题,而且是针对早期版本的实体框架,所以我希望现在有答案.
There are some similar questions on this site, but they never really solved the problem and they were for earlier versions of entity framework, so I'm hoping that there is an answer now.
推荐答案
这是一个简单的解决方案,使用开关将特定的 Type
关联到表.您还可以维护使用某种 Dictionary<string, Type>
对象.
Here's a simple solution using a switch to associate a particular Type
to a table. You could also maintain use some sort of Dictionary<string, Type>
object.
var tableName = "Table1";
// Get proper return type.
Type returnType;
switch(tableName) {
case "Table1":
returnType = typeof(Table1EntityType);
break;
case "Table2":
returnType = typeof(Table2EntityType);
break;
}
var query = context.Set(returnType);
// Filter against "query" variable below...
var result = query.Where(...);
-或-
var tableName = "Table1";
Dictionary<string, Type> tableTypeDict = new Dictionary<string, Type>()
{
{ "Table1", Table1Type },
{ "Table2", Table2Type }
};
var query = context.Set(tableTypeDict[tableName]);
// Filter against "query" variable below...
var result = query.Where(...);
针对实体框架修改
根据@thepirat000 的建议使用 typeof
Use typeof
per @thepirat000 's suggestion
这篇关于Entity Framework linq 中的动态表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!