Dynamic LINQ Compare Dates in Entity Framework

.net dynamic-linq entity-framework linq linq-to-entities


I am using the dynamic linq library with entity framework and want to compare dates. I have succesfully extended the library based on the following SO article here However what I can not seem to do is to get the library to compare just the date portion of the DateTime property of my entity object as I would do with a normal linq expression.

What I am trying to do is have the dynamic linq create a lambda like this:

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

Rather than:

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

Any ideas on this would be much appreciated.

5/23/2017 10:26:43 AM

Accepted Answer

The Dynamic Linq parser supports all public members of the System.DateTime type, including the Date property. So you could do something like

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

UPDATE: If you are using Entity Framework this example will not work, since it does not support translating the DateTime.Date property into SQL. Normally you could use the EntityFunctions.TruncateTime() function to achieve the same effect, but this function is not accessible to the Dynamic Linq parser without modifications. However, you should be able to to do something similar to the following (haven't tested):

var query = items.Where("CreatedDate.Value.Year == @0.Year && CreatedDate.Value.Month == @0.Month && CreatedDate.Value.Day== @0.Day", comparisonDate);
7/11/2013 2:44:02 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow