Can I write case when query in entity framework core and linq?

Viewed 304

My query is like following, (postgresql)

  SELECT split_part(grp.agerange, '*',2) as age_range,
         round(sum(salary)) AS total
  FROM
   (
       SELECT salary,
              CASE
                  WHEN(date_part('year', age(birth_date)) >  0  AND date_part('year', age(birth_date)) <= 8)   THEN  '0 - 8 age'
                  WHEN(date_part('year', age(birth_date)) >  8  AND date_part('year', age(birth_date)) <= 16)   THEN '8 - 16 age'
                  WHEN(date_part('year', age(birth_date)) >  16  AND date_part('year', age(birth_date)) <= 24)   THEN '16 - 24 age'
                  WHEN(date_part('year', age(birth_date)) >  24)  THEN '24 < age'   ELSE 'Unknown'
               END as agerange
       FROM sde.employee
    ) grp
  GROUP BY grp.agerange
  ORDER BY grp.agerange;

So can I create a query in entity framework core 3.0 Employee model using linq?

public class Employee{
   public string Id {get;set;}
   public string Name {get;set;}
   public decimal Salary {get;set;}
   public DateTime? BirthDate {get;set;}
}

And from my dabase context:

var grouped = _context.Employees.Group(????

Birthdate is Nullable type.

1 Answers

You can just use the conditional operator ?, or an if statement in the Select statement, then group by that result....

var grouped = _context.Employees
    .Select(e => new { AgeRange = e.birth_date.Year > 24 ? "24 < age" : etc.});
    .Group(e => e.AgeRange);
Related