问题
i heard people saying date time comparison do not work just due to time part because datetime has time part.
in sql i always compare datetime like this way and it works fine
select * from employee
where convert(varchar,dob,112) > '20111201' // this yyyymmdd format.
how could i simulate this in a LINQ query?
回答1:
The one thing to keep in mind is that operations on DateTime structs that represent database columns don't translate to SQL. So, you cannot write a query like:
from e in EfEmployeeContext
where e.DOB.Date > new DateTime(2011,12,01);
... because e.DOB represents the DOB column in the database, and EF won't know how to translate the Date sub-property.
However, there's an easy workaround depending on what dates you want:
If you want to include all employees that have a DOB on 12/01/2011 as well as those born after that date, then simply query:
from e in EfEmployeeContext where e.DOB > new DateTime(2011,12,01);
If you want to include only employees born after 12/01/2011, then query:
from e in EfEmployeeContext where e.DOB >= new DateTime(2011,12,02);
In short, the criteria, meaning a constant or literal DateTime you're comparing against, can be set up however you want. You just can't make radical modifications to properties that represent DB columns within the where predicate. That means you can't compare one DateTime column to a projection of another DateTime column, for instance:
//get all employees that were hired in the first six months of the year
from e in EfEmployeeContext
where e.HireDate < new DateTime(e.HireDate.Year, 7, 1);
回答2:
If you're using .NET 4 or above, just use the EntityFunctions.TruncateTime helper method. This will translate this type of datetime-to-date conversion to SQL for you.
from e in EfEmployeeContext
where EntityFunctions.TruncateTime(e.DOB) > new DateTime(2011,12,01);
来源:https://stackoverflow.com/questions/12412231/how-do-i-perform-date-part-comparison-in-ef