在 lambda 表达式中转换可为 null 的 DateTime

Cast a nullable DateTime in a lambda expression

我想使用 EF6 从我的数据库 CALENDRIER 中获取 2019 年的所有对象,但 EF6 生成可为空的 DateTimes "DateTime?" 而不是通常的 DateTimes。因为我只想要年份,所以我可以使用 DateTime 中的 Year 字段来过滤我的列表,但它不适用于可为 null 的 DateTime。基本上我想像这样使用它:

_db.CALENDRIERs.Where(c => c.CALE_DATE.Year == year).ToList();

但我收到以下错误:

'DateTime?' does not contain a definition for 'Year' and no accessible extension method 'Year' accepting a first argument of type 'DateTime?' could be found...

如何将它们隐式转换到我的 lambda 表达式中?

您必须访问可空类型的 Value 字段:

DateTime? nullableDt = DateTime.Now;
int year = nullableDt.Value.Year;

首先检查CALE_DATE是否有值,然后使用.Value

_db.CALENDRIERs.Where(c => c.CALE_DATE.HasValue && c.CALE_DATE.Value.Year == year).ToList();

您可以先检查 DateTime 对象是否不为空,即它是否具有值,然后您可以从中获取年份 属性

_db.CALENDRIERs.Where(c => c.CALE_DATE.HasValue && c.CALE_DATE.Year == year).ToList();