![](/img/trans.png)
[英]LINQ to Entities does not recognize the method 'System.String get_Item(Int32)' method, and this method cannot be translated into a store expression
[英]LINQ to Entities does not recognize the method 'System.String get_Item(Int32)' method
我正在嘗試為類列表分配一個值,但它似乎不喜歡我的 select 語句中的“外部”值。
C# .dll 文件中的代碼(在 Visual Studio 中編譯時沒有錯誤):
Dictionary<int, string> My_dict1 = new Dictionary<int, string>();
My_dict1.Add(0, "Welcome");
var inv = traces.Select(x => new TraceLabelData
{
Name = My_dict1[0]
}).ToList();
在 LINQPAD 中引用和運行時出錯:
NotSupportedException LINQ to Entities 無法識別方法“System.String get_Item(Int32)”,並且此方法無法轉換為存儲表達式。
如果我用一個普通字符串替換 My_dict[0] ,它就可以工作,如果我用一個普通字符串的變量替換它,它就可以工作。 它不適用於字典,也不適用於返回字符串的函數。
您傳遞給 LINQ-to-Entities 的表達式不會被計算。 它們被解析,然后轉換為 SQL 語句,然后由 SQL Server 進行評估。 服務器不知道您的字典是什么,但它知道什么是普通字符串,這就是為什么它只有在您更改代碼以使用字符串時才起作用。
這種情況下的解決方案是在 LINQ 語句之前從字典中檢索您需要的值,然后直接使用檢索到的值。
Linq-to-Entities 只能使用與您的后端數據庫服務器兼容的 Linq 操作。 顯然您的My_dict1
對象不存在於遠程服務器中(即您不能從原始 SQL 中使用它)。 相反,在涉及內存字典之前,使用AsEnumerable()
、 ToList()
或ToListAsync()
將對象拉入內存:
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add( 0, "Welcome" );
traces
.AsEnumerable()
.Select( t => new TraceLabelData() { Name = dict[0] } )
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.