从LINQ到SQL的LINQ

时间:2019-05-13 22:36:54

标签: c# .net entity-framework linq

我创建了一个有效的sql查询:

select CONVERT(date, C.tDate) as dt, count(O.Id) as cnt  from [Calendar] C
left outer join [Order] O
on C.tDate = CONVERT(date, O.Dt)
group by CONVERT(date, C.tDate)
order by CONVERT(date, C.tDate)  

我想用LINQ重写它:

var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from pl in pp.DefaultIfEmpty()
group c by DbFunctions.TruncateTime(pl.Dt.Value) into g
orderby g.FirstOrDefault().tDate
select new { date = g.FirstOrDefault().tDate, cnt = g.Count() }).ToList();

我从sql查询中的日历中获取所有行,但在LINQ查询中不获取空行(右侧)。 如何在LINQ中获取所有日历行。

已添加: 然后我尝试:

var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from o in pp.DefaultIfEmpty()
group pp by DbFunctions.TruncateTime(o.Dt) into g2
select new { date = g2.Key, cnt = g2.Count() }).ToList();

我看到了这个:

{ date = null, cnt = 1062 } 
{ date = {25.01.2019}, cnt = 4 }
{ date = {26.01.2019}, cnt = 7 }
{ date = {27.01.2019}, cnt = 16 }
{ date = {28.01.2019}, cnt = 5 }

我想获取所有日期,而不是null ...

1 个答案:

答案 0 :(得分:0)

这个:

var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from o in pp.DefaultIfEmpty()
group pp by DbFunctions.TruncateTime(c.tDate) into g2
orderby g2.Key
select new { date = g2.Key, cnt = g2.FirstOrDefault().Count() }).ToList();