6

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.

Community
  • 1
  • 1
Cragly
  • 3,554
  • 9
  • 45
  • 59

1 Answers1

4

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);
luksan
  • 7,661
  • 3
  • 36
  • 38
  • I am actually passing in a filter expression (created higher up the app tier) to an IQuerable extension method which creates the Where clause ie 'CreatedDate == 2012/08/01'. Its possible that I could alter the expression in my MVC Controller to include the additional properties as you have highlighted in your example and see if that works. Apologies I should have explained in more detail but was trying to keep as much to the point as possible. – Cragly Aug 28 '12 at 21:51
  • Created the query expression further up the stack and worked like a charm. Thanks for the help. – Cragly Aug 29 '12 at 20:59
  • That gives me the error "The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported." – CoderDennis Jul 08 '13 at 17:43
  • @CoderDennis, that is because Entity Framework for some reason does not support the Date property. I updated my answer with an explanation. – luksan Jul 11 '13 at 14:44
  • @luksan - Awesome, I was looking for this answer from 9 hrs. thanks – Nikhil Chavan Sep 23 '13 at 14:00