Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter by nullable datetime field using Linq

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?

like image 698
user1000742 Avatar asked Feb 07 '23 10:02

user1000742


1 Answers

Use value property of nullable date

ent.MyTable.Where(e => e.MyDate.HasValue && e.Date.Value.Day == 12);
like image 152
Mostafiz Avatar answered Feb 08 '23 23:02

Mostafiz