Linq to sql 如何在LINQ to SQL where条件中处理可为空的日期时间?

Linq to sql 如何在LINQ to SQL where条件中处理可为空的日期时间?,linq-to-sql,Linq To Sql,我需要选择一个尚未过期的优惠券列表。即: where Coupon.ExpiresOn > DateTimeUtc.Now 问题是Coupon.ExpiresOn是DateTime(DateTime?)的可空值。上述代码不会返回优惠券.ExpiresOn中具有空值的优惠券。如何将其更改为返回空值?感谢您的帮助。在where语句中添加或: where !Coupon.ExpiresOn.HasValue || Coupon.ExpiresOn.Value > DateTimeUtc.

我需要选择一个尚未过期的优惠券列表。即:

where Coupon.ExpiresOn > DateTimeUtc.Now

问题是Coupon.ExpiresOn是DateTime(DateTime?)的可空值。上述代码不会返回优惠券.ExpiresOn中具有空值的优惠券。如何将其更改为返回空值?感谢您的帮助。

在where语句中添加或:

where !Coupon.ExpiresOn.HasValue || Coupon.ExpiresOn.Value > DateTimeUtc.Now

在where中允许空值,如下所示:

其中,优惠券.ExpiresOn==null|| 优惠券.ExpiresOn>DateTimeUtc.Now


事实上,不是。Linq to SQL会使您的C#短路,所以实际上语句的两边都会被调用。您的答案仍然正确,但您必须小心记住,您在这里使用的是LINQtoSQL(至少提问者是这样的)。SQL Server不会短路,也不会进行区分大小写的比较,因此您必须密切关注Linq的使用方式。@matmc3这是一个非常好的观点,我没有仔细考虑。我已经更新了我的答案。谢谢