SQL到LINQ C#Entity Framework

时间:2014-07-01 11:19:13

标签: c# sql linq entity-framework

我正在将所有直接 SQL 程序转换为 Entity Framework 。 所以我需要 LINQ LE

但是我无法在LINQ中执行此操作:

SELECT 
    a.abteilung, 
    sum(d.kosten) 
FROM 
    tdaten d, 
    abteilung a 
WHERE 
    d.sourcenr = a.sourcenr AND
    d.datum between '" + string.Format("{0:yyyy-MM-dd}", DTP_from.Value) + "' 
        and '"+string.Format(format: "{0:yyyy-MM-dd}", arg0: DTP_to.Value)+"'
GROUP BY 
    a.abteilung;", _con);

由于

2 个答案:

答案 0 :(得分:0)

选项。
整个可以分为LINQ中的3个子查询。

  1. 获取记录
  2. 取总和
  3. 结果组。
  4. 以下是查询:

     var results = from a in abteilung
              join d in tdated on d.sourcenr equals a.sourcenr
              where 
              d.dateum >= fromDate && d.datum <= ToDate.AddDays(1)
              select  new {a.abteilung,  d.kosten};
    
        var sumOfKotsen = results.Sum(x=>x.kosten);
    
        var groupResult = results.GroupBy(x=>x.abteilung);
    

    假设dateFromToDate是DateTime对象。

答案 1 :(得分:0)

这样的东西?

from a in abteilung 
join d in tdaten 
   on a.sourcenr equals d.sourcenr
where d.datum >= DTP_from.Value && d.datum <= DTP_to.Value
group d by a.abteilung into g
select new
{
  abteilung = g.Key,
  kosten = g.Sum(d => d.kosten)
}