LINQ to Entities 无法识别方法 'System.String get_Item(Int32)' 方法

LINQ to Entities does not recognize the method 'System.String get_Item(Int32)' method

我正在尝试为 类 的列表赋值,但它似乎不喜欢我的 select 语句中的 "outside" 值。

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 does not recognize the method 'System.String get_Item(Int32)' method, and this method cannot be translated into a store expression.

如果我将 My_dict[0] 替换为普通字符串,它就可以工作;如果我将它替换为变量,即普通字符串,它就可以工作。它不适用于字典,也不适用于 returns 字符串的函数。

您传递给 LINQ-to-Entities 的表达式不会被计算。它们被解析,然后转换为 SQL 语句,然后由 SQL 服务器评估。服务器不知道您的字典是什么,但它确实知道纯字符串是什么,这就是为什么它仅在您更改代码以使用字符串时才起作用。

这种情况下的解决方案是在 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();