I'm trying to filter all rows in an SQL table that have a specific date. It works if the column is not nullable, but fails if it is.
This works for not nullable datetime fields:
ent.MyTable.Where(e => e.MyDate.Day == 12);
Obviously this works not for nullable datetime fields. After doing some search on the Internet, I found many "solutions" to this problem that look like to following:
ent.MyTable.Where(e => e.MyDate != null && e.MyDate.Day == 12);
Unfortunately this does not work for me either. And it is understandable why if I consider this error message:
'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?)
I want to avoid fetching all SQL rows and then filter in .NET since I am only interested in a very small number of rows. Is there any other way that I don't see at the moment?
Use value property of nullable date
ent.MyTable.Where(e => e.MyDate.HasValue && e.Date.Value.Day == 12);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With