Asp.net-Mvc

Entity Framework linq 中的動態表名

  • April 29, 2022

我將 Entity Framework 6 與 ASP.Net MVC 5 一起使用。當使用數據庫上下文對象時,有沒有辦法將變數用於表名,而無需手動編寫查詢?

例如:

var tableName = "NameOfTable";

result = context.tableName.Find(...);

我知道特定程式碼不起作用,因為 tableName 沒有在上下文中定義,但是有沒有辦法達到預期的效果?

這個網站上有一些類似的問題,但他們從來沒有真正解決過這個問題,而且它們是針對早期版本的實體框架的,所以我希望現在有答案。

這是一個簡單的解決方案,它使用開關將特定對象Type與表相關聯。您還可以維護使用某種Dictionary<string, Type>對象。

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(...);

編輯:針對實體框架進行了修改

EDIT2:typeof按照@thepirat000 的建議使用

引用自:https://stackoverflow.com/questions/31033055