user386167
user386167

Reputation:

How to handle a nullable DateTime in a LINQ-to-SQL where condition?

I need to select a list of coupons that have not expired yet. That is:

where Coupon.ExpiresOn > DateTimeUtc.Now

Problem is that Coupon.ExpiresOn is a nullable of DateTime (DateTime?). The code above does not return coupons with null values in Coupon.ExpiresOn. How could I change it to return null values? Thank you for your help.

Upvotes: 3

Views: 5506

Answers (2)

sgriffinusa
sgriffinusa

Reputation: 4221

Add an or to your where statement:

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

Upvotes: 5

Tahbaza
Tahbaza

Reputation: 9546

allow nulls in your where, like so:

where Coupon.ExpiresOn == null || Coupon.ExpiresOn > DateTimeUtc.Now

Upvotes: 5

Related Questions