I have an entity framework's EDMX generated class having a DOB (Date Of Birth) property.
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.
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.
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.
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.
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
.
var want = new DateTime(2015, 2, 21);
Expression<Func<Contact, bool>> cntExpression = p =>
p.DOB.HasValue && want == p.DOB.Value.Date;