简体   繁体   English

实体框架ToString方法

[英]Entity Framework ToString method

Following code block throws error. 以下代码块抛出错误。

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression. LINQ to Entities无法识别方法'System.String ToString()'方法,并且此方法无法转换为存储表达式。

db.tbOnIgmHawbDetails
  .Where(s => !db.tbImpoExaminations.Any(x => x.Hawb.ToString() == s.Hawb) && s.AwbNo == p)
  .Select(s => s.Hawb).ToList();

Any suggestion? 有什么建议吗? why this happen and what is the solution? 为什么会这样,解决方案是什么?

You could try with SqlFunctions.StringConvert ... Use the decimal conversion: 您可以尝试使用SqlFunctions.StringConvert ...使用decimal转换:

SqlFunctions.StringConvert((decimal)p.x.Hawb).TrimLeft() == ...

(the TrimLeft is necessary because the STR function of SQL will right align the number) TrimLeft是必要的,因为SQL的STR函数会正确对齐数字)

If s.Hawb is already string type (the error message suggests so), then remove the part .ToString() from your query. 如果s.Hawb已经是字符串类型(错误消息暗示如此),则从查询中删除部分.ToString()

The reason for it is that in LINQ2SQL, you can only use those language constructs that can be translated into SQL. 原因是在LINQ2SQL中,您只能使用那些可以转换为SQL的语言结构。 For example, if you try to use RegEx in your C# expression, then SQL does not have a corresponding construct for RegEx, and thus LINQ cannot translate and execute your query. 例如,如果您尝试在C#表达式中使用RegEx,则SQL没有RegEx的相应构造,因此LINQ无法转换和执行您的查询。

Easily add .AsEnumerable() before the .ToString() and those methods that L2E doesn't support: .ToString()和L2E不支持的方法之前轻松添加.AsEnumerable()

var asen = db.tbOnIgmHawbDetails.AsEnumerable();

var result =  asen.Where(s => !asen.Any(x => x.Hawb.ToString() == s.Hawb) && s.AwbNo == p)
  .Select(s => s.Hawb).ToList();

That should works. 这应该有效。 However if not, try to perform your query by linq-to-objects syntax: 但是,如果没有,请尝试通过linq-to-objects语法执行查询:

var result = from a in asen
             where ...
             select ...;

do not use ToString 不要使用ToString

just use like 就像使用一样

x.Hawb + "" == s.Hawb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM