Property 'Int32 Year' is not defined for type 'System.Nullable`1[System.DateTime]' When comparing year in two dates

c# entity-framework entity-framework-core

Question

I've got strange exception when comparing year in datetime.

sample code:

_dbContext.Details.Where(x => x.Person.Birth.Year == date.Year);

Where both Birth and date are not nullable DateTime.

Exception message:

Message: System.ArgumentException : Property 'Int32 Year' is not defined for type 'System.Nullable`1[System.DateTime]'

I tried to run the code from unit tests with database set up in memory.

1
-2
7/24/2017 3:40:23 PM

Accepted Answer

My model definition was wrong and I didn't specify foreign key correctly.

It looked similar to that (after renaming from PerId to PersonId the problem was gone):

public class Person
{
    public int Id {get; set;}
    public DateTime Birth {get; set;}
}

public class Details 
{
    public int Id {get; set;}
    public int PerId {get; set;}
    public Person Person {get; set;}
}
0
7/24/2017 3:41:07 PM

Popular Answer

So, it seems you have "DateTime?" instead of "DateTime". That way, you have to check something like that:

_dbContext.Details.Where(x => date.HasValue && (x.Person.Birth.Year == date.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