在将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属性中时间的日期。
答案 0 :(得分: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
的字段。从长远来看,这是值得的。