Friday 27 February 2015

Simple Date search in LINQ c#

The main problem faced in my recent project is the date search in LINQ .

Generally, Date search we have to check each and every datepart individually.
Example is mentioned below

(t.LastModifiedDate.Value.Day >= receivedFromDate.Value.Day &&
t.LastModifiedDate.Value.Month >= receivedFromDate.Value.Month &&
t.LastModifiedDate.Value.Year >= receivedFromDate.Value.Year)
&&
(t.LastModifiedDate.Value.Day <= receivedToDate.Value.Day &&
t.LastModifiedDate.Value.Month <= receivedToDate.Value.Month &&
t.LastModifiedDate.Value.Year <= receivedToDate.Value.Year)


It will look for individual date part, where code looks very large.


Therefore, I was searching for other alternative for DateTime search
then got know about a function which is built in EntityFramework
System.Data.Entity for version 6 and above

Function name is DbFunctions 
Example is shown below


(DbFunctions.TruncateTime(t.ContractDate)>=
receivedFromDate.Value)
&&
(DbFunctions.TruncateTime(t.ContractDate)>=
receivedToDate.Value)


In earlier versions of Entity Framework the function name was


EntityFunctions.TruncateTime()



I hope it is very small tip but it may help guys who are needed with.