0

In my Entity (Sale) has a type of DateTime column Date.

I used following lambda expression to get the latest TrNo from that table. But always it gives me Null. Because it also compares the Time part of the column. Actually I wanted to compare the Date part of the column.

db.Sales.OrderByDescending(O => O.Date).Where(O => O.Date == DateTime.Now ).Select(O => O.TrNo).FirstOrDefault();

Please help me to get the build the right code. (My db is MySQL)

Thanks!

2 Answers2

2

If O.Date is a Date, simply compare it against DateTime.Now.Date, since DateTime.Now will return both the Date & Time. If O.Date is actually a DateTime, simply do the same, O.Date.Date == DateTime.Now.Date.

eandersson
  • 25,781
  • 8
  • 89
  • 110
  • I'm not sure that EF can transform this expression into sql code. – Kirill Bestemyanov Feb 01 '13 at 11:57
  • Thanks but it throws, `The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.` – Seevali H Rathnayake Feb 01 '13 at 12:01
  • Yea. It looks like you are correct. I would recommend that the OP takes a look at this. http://stackoverflow.com/questions/1478215/how-to-compare-only-date-components-from-datetime-in-ef – eandersson Feb 01 '13 at 12:02
  • 1
    Just move your DateTime value to separate variable, and then use it inside LINQ query – xwrs Feb 01 '13 at 12:03
0

If you only want to test the date portion of the datetime try this.

db.Sales.OrderByDescending(O => O.Date).Where(O => O.Date == DateTime.Now.Date ).Select(O => O.TrNo).FirstOrDefault();
Tom Styles
  • 1,098
  • 9
  • 20