[英]LINQ to Entities does not recognize the method 'System.String ToString(System.Object)' method error occurs with nullable fields
I have an entity framework's EDMX generated class having a DOB (Date Of Birth) property. 我有一个具有DOB(出生日期)属性的实体框架的EDMX生成的类。
public partial class Contact : EntityBase
{
public Contact()
{
}
public Nullable<System.DateTime> DOB { get; set; }
}
I created a LINQ expression for searching records using a string value "2015-02-21" against DOB. 我创建了一个LINQ表达式来使用针对DOB的字符串值“ 2015-02-21”来搜索记录。
Expression<Func<Contact, bool>> cntExpression = p => Convert.ToString(p.DOB).ToLower().Trim().Contains("2015-02-21");
I used business logic class's method to filter records using the above LINQ expression. 我使用业务逻辑类的方法来使用上面的LINQ表达式过滤记录。
IQueryable<Contact> qryContact = _cntMgr.GetFiltered(cntExpression);
But as you can see that DOB is a nullable property, so it throws error when below code starts looping through records existing in the above IQueryable instance. 但是,您可以看到DOB是可为空的属性,因此当以下代码开始循环遍历上述IQueryable实例中存在的记录时,它将引发错误。
foreach (var contact in qryContact)
{
if (contact!=null)
{
// some code gets execute here..
}
}
The error I get is this: 我得到的错误是这样的:
LINQ to Entities does not recognize the method 'System.String ToString(System.Object)' method, and this method cannot be translated into a store expression.
I already know that System.String ToString isn't supported in Linq to Entities, but I need a solution or a workaround for this problem. 我已经知道Linq to Entities不支持System.String ToString,但是我需要解决此问题的方法或解决方法。
Kindly help me in fixing this issue. 请帮助我解决此问题。
Thanks in advance. 提前致谢。
Check for a null 检查是否为空
Expression<Func<Contact, bool>> cntExpression = p =>
p.DOB.HasValue
&& Convert.ToString(p.DOB.Value).ToLower().Trim().Contains("2015-02-21");
An improvement would be to just compare the date component of the DateTime
. 一种改进是仅比较DateTime
的日期部分。
var want = new DateTime(2015, 2, 21);
Expression<Func<Contact, bool>> cntExpression = p =>
p.DOB.HasValue && want == p.DOB.Value.Date;
我认为您无需进行转换,可以将代码更改为:
Expression<Func<Contact, bool>> cntExpression = p => p.DOB.HasValue && p.DOB.Value.ToShortDateString() == "2015-02-21";
Replacing the expression to this will work ! 将表达式替换为此将起作用!
Expression<Func<Contact, bool>> cntExpression = p => p.DOB.HasValue && p.DOB.Value.Year == Convert.ToInt32("2015") && p.DOB.Value.Month == Convert.ToInt32("02") && p.DOB.Value.Month == Convert.ToInt32("21");
Lemme know if you face any further issues on this. Lemme知道您是否在此方面还有其他问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.