So I have been trying to convert my L2S code to EF 4.1, mostly because L2S has become annoyingly hard to do schema updates for. It unfortunately seems like EF's linq capabilities are extremely lacking, and I am unsure of how to write this query in EF, as it seems like you cannot do date arithmetic in EF. My Linq-To-Sql code is:
// Check for any scheduled requests that have not started within the last 24 hours since the scheduled time on the previous day
DateTime currentDate = DateTime.Now.Date;
req = _context.TestRequests.Where(x => x.scheduled_time != null
&& x.TestRequestRuns.Count > 0
// Make sure the current time is after the request's scheduled time
&& DateTime.Now > (currentDate + x.scheduled_time.Value)
// Check to see if the scheduled time today is later than the last test run start time, if so start a test run
&& (currentDate + x.scheduled_time.Value) >
x.TestRequestRuns.Where(y => !y.reran)
.OrderByDescending(y => y.start_dt)
.First().start_dt)
.OrderBy(x => x.scheduled_time)
.FirstOrDefault();
This is for a system to run automated tests at scheduled times on a daily basis. The basic idea behind this query is I am retrieving test requests that has been run at least once, that have a scheduled time of prior to right now, and test requests that have not been run since the last scheduled time.
This query works perfectly with _context
is hooked up to the L2S data context, but when used against my EF 4.1 DbContext
I get an ArgumentException
with the message DbArithmeticExpression arguments must have a numeric common type.
.
Does anyone know why this doesn't work and how I can fix this for EF 4.1?
Edit:
To be more specific, EF seems incapable of performing Date Arithmetic and (currentDate + x.scheduled_time.Value)
is what is causing 开发者_StackOverflow中文版the exception.
Without knowing the data type of the scheduled_time
field, I would suspect the errant lines are the two where you attempt the calculation:
currentDate + x.scheduled_time.Value
I would imagine that you are attempting to add a TimeSpan
to a DateTime
object, which gives a sort of type mismatch in EF4.1. Why don't you call .Add() on currentDate
and see if this works a bit better:
currentDate.Add(x.scheduled_time.Value)
Check out, http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.aspx. They may help you when trying to do Date functions in EF. I use the DatePart stuff alot.
精彩评论