使用 Linq 按可为空的日期时间字段过滤

Filter by nullable datetime field using Linq

我正在尝试筛选 SQL table 中具有特定日期的所有行。如果该列不可为 null 则它会起作用,但如果它是则失败。

这适用于不可为空的日期时间字段:

ent.MyTable.Where(e => e.MyDate.Day == 12);

显然这不适用于可为空的日期时间字段。在互联网上做了一些搜索后,我发现很多 "solutions" 这个问题看起来像下面这样:

ent.MyTable.Where(e => e.MyDate != null && e.MyDate.Day == 12);

不幸的是,这对我也不起作用。如果我考虑此错误消息,这是可以理解的:

'System.Nullable' does not contain a definition for 'Day' and no extension method 'Day' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)

我想避免获取 所有 SQL 行然后在 .NET 中进行过滤,因为我只对极少数行感兴趣。还有其他我目前看不到的方法吗?

使用可为 null 的日期

的值 属性
ent.MyTable.Where(e => e.MyDate.HasValue && e.Date.Value.Day == 12);

试试这个:

 ent.MyTable.Where(e => e.MyDate.HasValue && e.MyDate.Value.Day == 12);