首页 > 解决方案 > 实体框架核心 where 子句额外条件

问题描述

我有这个简单的查询,问题是End属性是DateTime?类型,我想包括这个值为空的记录,但我似乎做不到。我尝试使用三元运算符,但仍然没有结果

await _context.Registos
    .Where(r => r.Start.Date >= DateStart.Date && r.End.HasValue ? r.End.Value <= DateEnd.Date : !r.End.HasValue )
    .AsNoTracking()
    .ToListAsync();

标签: c#entity-framework-core

解决方案


一种更清洁的方式,如下所示:

await _context.Registos
    .Where(r => r.Start.Date >= DateStart.Date 
        && (r.End == null || r.End.Value <= DateEnd.Date))
    .AsNoTracking()
    .ToListAsync();

推荐阅读