【问题标题】:Exception on try to compare only date from datetime with ef core 3.0尝试仅将 datetime 中的日期与 ef core 3.0 进行比较时出现异常
【发布时间】:2019-11-11 19:59:14
【问题描述】:

将 ef core 更新到 3.0 后,当尝试截断时间并仅比较 datetime 中的日期时,ef core 返回错误:

The LINQ expression 'Where<Category>(\n    source: DbSet<Category>, \n    predicate: (c) => c.CreateAt.Date == DateTime.Now.Date)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

对于这个查询:

Context.Category.Where(c => c.CreateAt.Date == DateTime.Now.Date).AsNoTracking().ToListAsync();

我只需要比较日期,而忽略 DateTimeOffSet 属性中的时间。

【问题讨论】:

    标签: c# asp.net-core .net-core .net-core-3.0 ef-core-3.0


    【解决方案1】:

    看来DateTime.Now 是这里的问题。

    我不知道数据,我不知道你是否存储时间组件,但有两个选项你可以尝试。

    如果您想比较两个时间戳,请将 .Now 从lamba 中取出并尝试以下操作。

    var today = DateTime.Now.Date; // Or DateTime.Today
    Context.Category.Where(c => c.CreateAt.Date == today ).AsNoTracking().ToListAsync();
    

    如果您想要今天的所有记录,可以尝试以下操作。

    var start = DateTime.Today;
    var end = Date.Time.Today.AddDays(1); // the following midnight
    
    var todaysCats = Context.Category.Where(c => c.CreateAt >= start && c.CreateAt < end ) // note '>=' and '<'
    

    顺便说一句。最好对CreatedAt-like 字段使用 Utc 时间戳。从长远来看,这是有回报的。

    【讨论】:

    • 但是我需要比较没有时间的日期
    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2010-12-01
    相关资源
    最近更新 更多