how to compare age with birthdate in where clause? Somthing like this code:
myRepository.Where(x =>
fromAge <= x.BirthDate.Age && x.BirthDate.Age <= toAge)
.Select(x).toList();
Data Types:
fromAge, toAge : int
x.BirthDate: DateTime
how to compare age with birthdate in where clause? Somthing like this code:
myRepository.Where(x =>
fromAge <= x.BirthDate.Age && x.BirthDate.Age <= toAge)
.Select(x).toList();
Data Types:
fromAge, toAge : int
x.BirthDate: DateTime
after searching, i ended up with this solution:
toDate = DateTime.Now.AddYears(-fromAge).Date.AddYears(1).AddDays(-1);
fromDate = DateTime.Now.AddYears(-toAge).Date.AddYears(-1).AddDays(+1);
consider changing "fromAge" to "toDate" and "toAge" to "fromDate". so:
myRepository.Where(x => fromDate <= x.BirthDate && x.BirthDate <= toDate)
.Select(x).toList();
I presume x.BirthDate
is a DateTime.
You can get a person's age given a DateTime representing their D.O.B. like so:
double age = Math.Floor(DateTime.Now.Subtract(BirthDate).TotalDays / 365.25m);
You can make this into an extension method:
public static int Age(this DateTime birthDate)
{
return (int)Math.Floor(DateTime.Now.Subtract(birthDate).TotalDays / 365.25m);
}
And then you can do:
myRepository.Where(x => fromAge <= x.BirthDate.Age() && x.BirthDate.Age() <= toAge).ToList();
Be advised however, if myRepository
is an EntityFramework DbSet
, this will not work. You will have to do myRepository.AsEnumerable().Where(// etc)
, otherwise you will get an exception.
Construct a WHERE clause in the following way
myRepository.Where(x =>
fromAge <= (Datetime.Now.Year - x.BirthDate.Year) && (Datetime.Now.Year - x.BirthDate.Year) <= toAge)
.Select(x).toList();
Assuming fromAge and toAge are years:
myRepository.Where(x => DateTime.Now.AddYears(-fromAge) <= x.BirthDate && x.BirthDate <= DateTime.Now.AddYears(-toAge)).ToList();
I think you have to add this to your BirthDate class:
[NotMapped]
public int Age {
get {
DateTime now = DateTime.Now;
int age = now.Year - BirthDate.Year;
if(now < BirthDate.AddYears(age)) age--;
return age;
}
}
this is make your age property for auto calculate from birthdate