Search code examples
c#.netlinqentity

Calculate persons age on given date than select from DB Entity LINQ


I have a query where I need to get and count all the job positions where the person was younger than 20 years old on the day of the employment.

I need to be more precise on the age since the code below is basic and can deviate by a year. If you could help me find a way to calculate age with something like dateDiff or some other solution. Keeping in mind that I need to do this for other ages too but this is curently my problem. Thanks.

CountJobPositions = (from query in queryAll
                  where query.jobPosition.StartDate.Year - query.person.DateOfBirth.Value.Year < 20
                  select query).Count()

Solution

  • I haven't used EF6 for some time but I believe that you need to use the System.Data.Entity.DbFunctions class. In this case, I think you would use this:

    where DbFunctions.AddYears(query.person.DateOfBirth, 20) > query.jobPosition.StartDate
    

    You might have to do a bit of jiggery-pokery to account for nullability but that should be basically it.