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

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

您好,我正在使用 linq 查询,该查询抛出错误 LINQ to Entities 无法识别方法 'System.String ToString(Int32)' 方法,并且此方法无法转换为存储表达式。

        List<string> resultMap = (from item in mapResult
                                  select Convert.ToString(item.ResultDE)).ToList();

以下语句中出现错误

        List<Result_DE> resultList = (from result in db.Result_DE
                                      where result.IsActive == "1"
                                      && resultMap.Contains(Convert.ToString(Convert.ToInt32(result.ID)))
                                      select result).ToList();

请告诉我编写此查询的正确方法。

如果你的item.ResultDEresult.ID是Int32的变量类型, 为什么不直接创建一个 List<Int32> ?

List<Int32> resultMap = (from item in mapResult
                              select item.ResultDE).ToList<Int32>();

List<Result_DE> resultList = (from result in db.Result_DE
                                  where result.IsActive == "1"
                                  && resultMap.Contains(result.ID)
                                  select result).ToList<Result_DE>();

您不能在 LINQ to Entities 语句中使用这些转换函数,它们无法转换为 SQL,您需要在内存中进行转换。但我认为你根本不需要这样做。

如果您只是使用 resultMap 来获取 resultList,通过 Results 过滤,其中 Id 出现在 mapResult 中,请执行以下:

var resultList = db.Result_DE
    .Where(r => r.IsActive == "1" && mapResult.Any(mr => mr.ResultDE == r.ID));
    .ToList();

如果 mapResult 是内存中的集合,而不是附加到 db 上下文的 IQueryable,您需要执行以下操作:

var resultIds = mapResult.Select(mr => mr.ResultDE).ToList();
var resultList = db.Result_DE
    .Where(r => r.IsActive == "1" && resultIds.Contains(r.ID));
    .ToList();

在调用任何方法(例如 ToString())之前,您需要使用 AsEnumerable() 将 LINQ to Object 转换。

使用 SqlFunctions.StringConvert 代替 Convert.ToString。

有人提出并回答了类似的问题here