如何在LINQ-to-SQL where条件中处理可为空的DateTime?

3 linq-to-sql

我需要选择尚未过期的优惠券列表.那是:

where Coupon.ExpiresOn > DateTimeUtc.Now
Run Code Online (Sandbox Code Playgroud)

问题是Coupon.ExpiresOn是DateTime(DateTime?)的可空.上面的代码不会在Coupon.ExpiresOn中返回具有空值的优惠券.我怎么能改变它以返回空值?谢谢您的帮助.

sgr*_*usa 5

将 or 添加到您的 where 语句中:

where !Coupon.ExpiresOn.HasValue || Coupon.ExpiresOn.Value > DateTimeUtc.Now
Run Code Online (Sandbox Code Playgroud)


Tah*_*aza 5

允许在你的位置使用空值,如下所示:

其中Coupon.ExpiresOn == null || Coupon.ExpiresOn> DateTimeUtc.Now