Dynamically comparing date values ​​in the Entity Framework

I am using linq dynamic library with entity infrastructure and want to compare dates. I have successfully expanded the library based on the following SO article here . However, I cannot get the library to compare only the date part of the DateTime property of my object object, as I would with a normal linq expression.

What I'm trying to do is create a dynamic linq creating lambda like this:

// Compare just dates p => p.CreatedDate.Value.Date == '2012/08/01' 

Instead

 // Compares date + time p => p.CreatedDate == '2012/08/01' 

Any ideas on this would be greatly appreciated.

+4
source share
1 answer

The Linq dynamic analyzer supports all public members of the System.DateTime type, including the Date property. So you can do something like

 DateTime comparisonDate = new DateTime(2012, 8, 1); var query = items.Where("CreatedDate.Value.Date == @0", comparisonDate); 

UPDATE If you use the Entity Framework, this example will not work because it does not support translating the DateTime.Date property into SQL. You can usually use the EntityFunctions.TruncateTime() function to achieve the same effect, but this function is not available to the Linq dynamic analyzer without changes. However, you should be able to do something similar to the following (not verified):

 var query = items.Where("CreatedDate.Value.Year == @0.Year && CreatedDate.Value.Month == @0.Month && CreatedDate.Value.Day== @0.Day", comparisonDate); 
+3
source

All Articles