尝试仅将日期时间的日期与 ef core 3.0 进行比较时出现异常

Exception on try to compare only date from datetime with ef core 3.0

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

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 的时间 属性。

看来 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 类字段使用 Utc 时间戳。从长远来看,这是有回报的。