如何让这个Linq-To-Sql查询在Entity Framework 4.1中运行?

时间:2011-06-21 18:19:49

标签: c# entity-framework entity-framework-4.1

所以我一直在尝试将我的L2S代码转换为EF 4.1,主要是因为L2S变得非常难以进行架构更新。遗憾的是,EF的linq功能似乎非常缺乏,我不确定如何在EF中编写此查询,因为看起来你不能在EF中进行日期算术。我的Linq-To-Sql代码是:

// 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();

这是系统每天在预定时间运行自动化测试。这个查询背后的基本思想是我正在检索已经运行至少一次的测试请求,其具有之前的预定时间,以及自上次计划时间以来尚未运行的测试请求。

此查询与_context完美配合,可以连接到L2S数据上下文,但是当用于我的EF 4.1 DbContext时,我会收到ArgumentException消息DbArithmeticExpression arguments must have a numeric common type.

有谁知道为什么这不起作用以及我如何解决这个问题?

修改

更具体地说,EF似乎无法执行日期算术,(currentDate + x.scheduled_time.Value)是造成异常的原因。

2 个答案:

答案 0 :(得分:2)

在不知道scheduled_time字段的数据类型的情况下,我怀疑错误的行是您尝试计算的两行:

currentDate + x.scheduled_time.Value

我认为您正在尝试向TimeSpan对象添加DateTime,这会在EF4.1中出现类型不匹配的情况。为什么不在currentDate上致电.Add(),看看这是否有效:

currentDate.Add(x.scheduled_time.Value)

答案 1 :(得分:1)

退房,http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.aspx。他们可能会帮助您尝试在EF中执行日期功能。我使用了DatePart的东西。