尝试仅将日期时间与EF Core 3.0进行比较时出现异常

在将ef core更新为3.0之后,如果尝试截断时间并仅比较日期时间中的日期,则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属性中时间的日期。

q33342074 回答:尝试仅将日期时间与EF Core 3.0进行比较时出现异常

这里似乎是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 '<'

顺便说一句。最好将Utc时间戳用于类似CreatedAt的字段。从长远来看,这是值得的。

本文链接:https://www.f2er.com/3121626.html

大家都在问