c# - 在 EntityFramework 中使用Where()会导致System.ArgumentException

标签 c# entity-framework

我有一个简单的方法,可以从 EntityFramework 中的 DbSet 获取所有最近修改的对象:

public List<JobModel> GetJobs()
{
    return db.Jobs
        .Include(j => j.JobStatus)
        .Include(j => j.JobResolution)
        .Include(j => j.Process)
        .Where(j => (DateTime.Now - j.ModifiedDtm).Days < 2)
        .ToList();
}

这工作正常,没有查询的 .Where(...) 部分。但是当我添加最后一点时,我得到以下三个异常:

Exception thrown: 'System.ArgumentException' in EntityFramework.dll

Exception thrown: 'System.ArgumentException' in EntityFramework.dll

Exception thrown: 'System.ArgumentException' in EntityFramework.SqlServer.dll

db.Jobs 中的所有行都具有有效值 ModifiedDtm,该值早于 DateTime.Now。我究竟做错了什么?我尝试将 Where() 方法移至 Include() 上方,但没有成功...

更新

感谢@CamiloTerevinto,我收到了一条信息更丰富的错误消息。虽然我还是不太明白这是什么意思...

DbArithmeticExpression arguments must have a numeric common type.

最佳答案

我很确定您正在寻找 DbFunctions.DiffDays功能:

return db.Jobs
    .Include(j => j.JobStatus)
    .Include(j => j.JobResolution)
    .Include(j => j.Process)
    .Where(j => DbFunctions.DiffDays(j.ModifiedDtm, DateTime.Now) < 2)
    .ToList();

关于c# - 在 EntityFramework 中使用Where()会导致System.ArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52930677/

相关文章:

c# - 验证 Entity Framework 模型类

c# - 如何在投影的 Entity Framework 对象中包含复杂的实体字段?

c# - 如何将现有类库转变为 worker 角色

c# - 更新关系实体

c# - 将按位枚举映射到 sql 列值

c# - Win7 上的 %TEMP% 中未找到文件

entity-framework - 实体类型 'BookId' 上的属性 'Library' 具有临时值。显式设置永久值或确保数据库是

entity-framework - Entity Framework 查询仅返回部分对象图

c# - 如何序列化列表?

c# - ASP.NET MVC URL 路由