I can't find how to compare a date entered by a user to a date on a table created by EF6. I'm using LINQ Extensions to search the DB and have tried multiple suggestions that compile, but fail during execution.
User Input:
DateTime userdate;
DateTime.TryParse(search.Value, out userdate);
Attempts so far:
a = dbContext.Messages.Where(x => x.Date.Date == userdate.Date); // doesn't compile
a = dbContext.Messages.Where(x => x.Date.Value.Date == userdate.Date); // error # 4
a = dbContext.Messages.Where(x => x.Date.ToString() == userdate.Date.ToString()); // issue #2
a = dbContext.Messages.Where(x => x.Date.Value.ToString() == userdate.Date.ToString()); // issue #2
a = dbContext.Messages.Where(x => Object.Equals(x.Date, userdate.Date)); // throws error #1
a = dbContext.Messages.Where(x => Object.Equals(x.Date.Date, userdate.Date)); // throws error #1
I've tried searching this a million times and find solutions that compile, yet always throw an error when executed.
There was a version of the ToString()
that worked, but it generated a long date string such as May 12, 2005 00:00:00
and trying to turn my userdate into a long date to compare just seems like it would create too much overhead when searching through millions of records.
I'm fresh out of ideas here.
Issues:
Unable to cast the type 'System.Nullable``1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
Doesn't find any matches, even with exact datetime
Magically works all of a sudden.
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Final solution Based on the selected answer, I found that the SqlFunctions class has a .DateDiff method which maps to the T-SQL DateDiff function. I used that to count the number of days between the two dates and selected only the ones that returned 0. That allowed me to compare the dates without having to do any conversion on the SQL side.
Where
directly on adbContext
rather than on a table within the context, btw...)