【问题标题】:LINQ to Entities does not recognize the method 'System.String ToString(Int32)'LINQ to Entities 无法识别方法“System.String ToString(Int32)”
【发布时间】:2015-07-25 13:32:30
【问题描述】:

您好,我正在使用一个 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();

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

【问题讨论】:

  • 我已尝试使用以下语句。它执行但没有输出List&lt;Result_DE&gt; resultList = (from result in db.Result_DE where result.IsActive == "1" &amp;&amp; resultMap.Contains(SqlFunctions.StringConvert(result.ID)) select result).ToList();
  • 您正在将字符串转换为 int 并再次转换回字符串?
  • result.ID的属性是什么
  • result.ID 的类型是什么?
  • 我正在将字符串转换为 int 并再次转换回字符串,因为没有任何效果,所以我尝试了各种组合

标签: c# .net linq entity-framework compiler-errors


【解决方案1】:

使用 SqlFunctions.StringConvert 而不是 Convert.ToString。

herehere

提出了类似的问题并得到了回答

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您不能在 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();
      

      【讨论】:

      • 我编辑了您的答案,现在它显示 Linq to Entities。如果您认为将 Linq To Sql 添加到组合中是值得的,您可以更新您的评论。恕我直言,这令人困惑,没有人使用“Linq to DB”一词
      • @Pawel 我同意,将保持原样。
      • 谢谢 :) .. mapResult.Any(mr =&gt; mr.ResultDE == r.ID) 工作
      【解决方案4】:

      如果您的 item.ResultDEresult.ID 是 Int32 的变量类型, 为什么不直接创建List&lt;Int32&gt;

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

      【讨论】:

        猜你喜欢
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-20
        • 2015-07-20
        • 2020-01-26
        相关资源
        最近更新 更多