我可以在Entity Framework Core和LINQ中编写case when查询吗?

3

我的查询类似于以下内容(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;

我能否在Entity Framework Core 3.0的Employee模型中使用LINQ创建查询?

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

根据我的数据库上下文:

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

生日是可空类型。

1个回答

0

你可以使用条件运算符“?”,或者在Select语句中使用if语句,然后按该结果进行分组...

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

不支持客户端的 GroupBy(EF Core 3.0 版本) - barteloma
不应该是客户端...展示你完整的查询,你在 group by 前使用了一个材料化运算符吗?比如 ToList 或者其他的什么? - Milney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接