Fixing Date comparison issue in C# LINQ


Now I will give you a hint on, how to compare date when using LINQ expressions along with Entity framework.

You can use  DbFunctions class of entity framework to accomplish our task. Lets say if you want to compare the date without considering the time part.

First of all add the following namespace in your code

using System.Data.Entity;

Following code takes the count of Products that were sold today

DateTime today = DateTime .Today;
int count = db.Product.Count(e => DbFunctions.TruncateTime(e.SaleDate).Value.CompareTo(DbFunctions.TruncateTime(today).Value)==0);


And we are done.
This is one way to remove the time part from the DateTime object so that we can make comparison with another DateTime object

Comments