将SQL Server查询转换为Entity Framework查询

时间:2018-02-11 14:35:34

标签: sql sql-server entity-framework linq

我有一个像这样的SQL Server查询:

select 
    month(fact_date) as month,
    sum(case when beef_dairy_stat = 1 and param_id = 1 then 1 else 0 end) as cnt
from 
    user_behave_fact
where 
    YEAR(fact_date) = 2018
group by 
    month(fact_date)
order by 
    month

结果

month   cnt
------------
  1     10
  2     20

现在我需要将此查询转换为相应的Entity Framework查询。

这是我目前的尝试:

var sql_rez_ICC = new List<Tuple<int, int>>();

sql_rez_ICC = db.user_behave_fact
                    .Where(x => x.fact_date.Value.Year == selected_year)
                    .GroupBy(y => y.fact_date.Value.Month)
                    .Select(y =>new { month = y.Select(x=>x.fact_date.Value.Month), icc_count = y.Count(x => x.beef_dairy_stat == true && x.param_id == 1) })
                    .AsEnumerable()
                    .Select(y => new Tuple<int, int>(y.month, y.icc_count))
                    .ToList();

然而,在第二个.Select,我在月份收到错误

  

无法从System.Collection.Generic.IEnumrable转换为int

1 个答案:

答案 0 :(得分:1)

y.Select(x=>x.fact_date.Value.Month)会返回IEnumerable<int>。请改用y.Key