This can be tricky because you need to make sure your birthday has passed this year, otherwise your age will be missing.
var query = from e in dataContext.Employees
let years = DateTime.Now.Year - e.BirthDate.Year
let birthdayThisYear = e.BirthDate.AddYears(years)
select new
{
Age = birthdayThisYear > DateTime.Now ? years - 1 : years
};
Executing this method has the advantage of calculating the age in the generated SQL query. This means that you do not need to iterate over the client-side result set to calculate age.
In case you are interested, he will create the following SQL:
DECLARE @p0 Int = 2013
DECLARE @p1 DateTime = '2013-02-14 09:08:46.413'
DECLARE @p2 Int = 1
SELECT [t2].[value] AS [years], [t2].[value2] AS [birthdayThisYear],
(CASE
WHEN [t2].[value2] > @p1 THEN [t2].[value] - @p2
ELSE [t2].[value]
END) AS [Age]
FROM (
SELECT [t1].[value], DATEADD(YEAR, [t1].[value], [t1].[BirthDate]) AS [value2]
FROM (
SELECT [t0].[BirthDate], @p0 - DATEPART(Year, [t0].[BirthDate]) AS [value]
FROM [Employees] AS [t0]
) AS [t1]
) AS [t2]
source
share