user1000742
user1000742

Reputation: 183

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?

Upvotes: 4

Views: 4664

Answers (2)

Mostafiz
Mostafiz

Reputation: 7352

Use value property of nullable date

ent.MyTable.Where(e => e.MyDate.HasValue && e.Date.Value.Day == 12);

Upvotes: 6

Sadique
Sadique

Reputation: 22841

Try this:

 ent.MyTable.Where(e => e.MyDate.HasValue && e.MyDate.Value.Day == 12);

Upvotes: 2

Related Questions