Filtering by Date efficiently

Filtering by Date efficiently

person using macbook air

Hey Guys,

Often we try to do some filtering with respect to date only, but that throws some errors like this.

Code Sample : Normally what we do

public static Expression<Func<CapturedData, bool>> IsEqualsDate(DateTime date)
{
    return p => p.CreatedDateTime.Date == date.Date || p.UpdatedCopyDate.HasValue && p.UpdatedCopyDate.Value.Date == date.Date;
}

The above code will surely throw out some error
The specified type member ‘Date’ is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

How to solve this?

Use of DbFunctions.TruncateTime(DateTime) will help us achieve this with ease. So Basically,

When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.

https://docs.microsoft.com : DbFunctions.TruncateTime Method

Code Sample : After Using DbFunctions.TruncateTime()

public static Expression<Func<CapturedData, bool>> IsEqualsDate(DateTime date)
{
    return p => DbFunctions.TruncateTime(p.CreatedDateTime) == date.Date || p.UpdateddCopyDate.HasValue &&  DbFunctions.TruncateTime(p.UpdatedCopyDate.Value) == date.Date;
}

Some times we do it another way and it goes something like this. Its also the way, but I dont suggest this to do as this one is the primitive way and can cause a lot of hassles and headaches while writing this code. I believe you wont do this. 😀

P.S. Please dont ever use the below code. I am striking this one so that you wont use this code.

public static Expression<Func<CapturedData, bool>> IsEqualsDate(DateTime date)
{
    return p=>p.CreatedDateTime.Year==today.Year && p.CreatedDateTime.Month==today.Month && p.CreatedDateTime.Day==today.Day || p=>p.UpdatedDateTime.Year==today.Year && p.UpdatedDateTime.Month==today.Month && p.UpdatedDateTime.Day==today.Day;
}

I hope this helps, Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *