Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Date function in LINQ to entities?

My method should return a list of user Notes so I did it like this:

  var saturday = DayOfWeek.Saturday;
  var query = from note in userNotes
  where note.NoteDate > lastMonth && note.NoteDate.DayOfWeek != saturday
        select note;

But i get this error:

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties.

Any ideas of how can I compare day of week using linq?

like image 294
gog Avatar asked Sep 17 '13 19:09

gog


2 Answers

Use SqlFunctions.DatePart static method. It will be transformed into DATEPART TSQL function call.

var saturday = (int)DayOfWeek.Saturday;
var query = from note in userNotes
            where note.NoteDate > lastMonth && SqlFunctions.DatePart("dw", note.NoteDate) != saturday
            select note;
like image 58
MarcinJuraszek Avatar answered Sep 19 '22 14:09

MarcinJuraszek


As I'm using Oracle, I couldn't use SqlFunctions class. Eventually I found a simple workaround for this problem:

Typically when you attempt to use a property that LINQ doesn't natively support, you'll need to create a concrete implementation of the collection before applying your LINQ constraints.

You can do this using the ToList() or AsEnumerable() methods prior to your Where clause as seen below :

 //Using the ToList() method
IEnumerable<CalendarDate> LessonDates = db.CalendarDates.ToList().Where(cd => cd.Date.DayOfWeek == DayOfWeek.Friday);

//Using the AsEnumerable() method
IEnumerable<CalendarDate> LessonDates = db.CalendarDates.AsEnumerable().Where(cd => cd.Date.DayOfWeek == DayOfWeek.Friday);

SOURCE: link

like image 3
tstancin Avatar answered Sep 23 '22 14:09

tstancin