【问题标题】:LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' methodLINQ to Entities 无法识别方法“Int32 Parse(System.String)”方法
【发布时间】:2015-09-20 10:13:36
【问题描述】:
var query = from d in db.mytable
         where d.Code == int.Parse(WebUtils.GetQueryString("Code"))
         orderby d.PersonInfo
         select d;

我收到以下错误

LINQ to Entities 无法识别方法“Int32 Parse(System.String)”方法,并且该方法无法转换为存储表达式。

我试图像这样重写 int.Parse(WebUtils.GetQueryString("Code")) int intCode = int.TryParse(WebUtils.GetQueryString("OfferCode"));

但还是报错

【问题讨论】:

标签: linq entity-framework linq-to-entities


【解决方案1】:

只需在查询上下文之外解析您的查询字符串:

int code = int.Parse(WebUtils.GetQueryString("Code"));

var query = from d in db.mytable
         where d.Code == code
         orderby d.PersonInfo
         select d;

【讨论】:

  • 我这样做了,但出现以下错误 - 输入字符串的格式不正确。我正在使用 EF 6.1
【解决方案2】:

您可以将“代码”字段转换为字符串,而不是将查询字符串转换为 int。 这应该有效:

var queryString = WebUtils.GetQueryString("Code");
var query = from d in db.mytable
     where SqlFunctions.StringConvert(d.Code) == queryString 
     orderby d.PersonInfo
     select d;

没有办法将字符串转换为 int。如果您使用 int.Parse,EF 不知道如何将其转换为 SQL

【讨论】:

  • 我做到了。谢谢。现在我收到另一个错误 - LINQ to Entities 无法识别方法“System.String GetQueryString(System.String)”方法,并且此方法无法转换为存储表达式。对此有什么想法吗?
  • 非常感谢。这样可行。我可以问点别的吗?我对这段代码有类似的问题 var query = from d in db.mytable select new { d.Code, EditModeratedComments = "改变" };无法将类型“System.Int32”转换为类型“System.Object”。 LINQ to Entities 仅支持转换 EDM 基元或枚举类型。谢谢
猜你喜欢
  • 2015-07-20
  • 2011-12-07
  • 1970-01-01
  • 2015-07-25
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
相关资源
最近更新 更多