Cast a nullable DateTime in a lambda expression

asp.net-mvc c# entity-framework-6

Question

Using EF6 I want to get all objects of the year 2019 from my database CALENDRIER, but EF6 generates nullables DateTimes "DateTime?" instead of usual DateTimes. Because I want only the year, I could use the Year field from the DateTime to filter my List, but it isn't available with a nullable DateTime. Basically I want to use it like this :

_db.CALENDRIERs.Where(c => c.CALE_DATE.Year == year).ToList();

But I get the following error :

'DateTime?' does not contain a definition for 'Year' and no accessible extension method 'Year' accepting a first argument of type 'DateTime?' could be found...

How can I cast them implicitely inside my lambda expression ?

1
0
7/22/2019 1:18:16 PM

Accepted Answer

First check to see if CALE_DATE has a value, and then use the .Value

_db.CALENDRIERs.Where(c => c.CALE_DATE.HasValue && c.CALE_DATE.Value.Year == year).ToList();
5
7/22/2019 1:20:36 PM

Popular Answer

You have to access the Value field of the nullable type:

DateTime? nullableDt = DateTime.Now;
int year = nullableDt.Value.Year;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow