select AVG(DATEDIFF(yyyy, (p.BirthDay), GETDATE()))
from Person p
I'm trying to translate this SQL query in a Linq to SQL query. My problems is with AVG() and DATEDIFF().
select AVG(DATEDIFF(yyyy, (p.BirthDay), GETDATE()))
from Person p
I'm trying to translate this SQL query in a Linq to SQL query. My problems is with AVG() and DATEDIFF().
Try something like below
EF6
double resultAverage = ctx.Person.Average(p => DbFunctions.DiffDays(p.BirthDay, DateTime.Now));
EF4
double resultAverage = ctx.Person.Average(p => SqlFunctions.DateDiff("day" ,p.BirthDay, DateTime.Now));
tryAlso
double resultAverage = ctx.Person.Average(p => (DateTime.Now - p.BirthDay).Days);
**I SOLVED doing like below: **
var query = (from A in ctx.Persons
select new {
AverageAge = ctx.Persons.Average(p => (Convert.ToInt32(DateTime.Now.ToString("yyyy")) - Convert.ToInt32(p.BirthDay)))
}).Distinct();
NOTE: i have solved it like above because p.Birthday returns a string in "yyyy" format.
Or i could do it also by applying "Take(1)" instead of "Distinct()" like below:
var query = (from A in ctx.Persons
select new {
AverageAge = ctx.Persons.Average(p => (Convert.ToInt32(DateTime.Now.ToString("yyyy")) - Convert.ToInt32(p.BirthDay)))
}).Take(1);