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 ?
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();
You have to access the
Value field of the nullable type:
DateTime? nullableDt = DateTime.Now; int year = nullableDt.Value.Year;