如何在My LINQ to EF查询中使用Left Join?

时间:2019-01-03 11:53:35

标签: asp.net sql-server linq linq-to-entities left-join

我的LINQ to EF查询是

var query = (from r in DB.region
             join g in DB.governorate on r.region_id equals g.region_id
             join s in DB.IndividualReports on g.governorate_id equals s.governorate_id
             join t in DB.AgencyReports on g.governorate_id equals t.governorate_id
             group new { r, s, t } by new { r.region_id, r.region_name }
             into grp
             select new
                {
                    RId= grp.Key.region_id,
                    RName=grp.Key.region_name,
                    IndividualCount = grp.Select(s => s.s.Id).Distinct().Count(),
                    AgencyCount = grp.Select(t => t.t.Id).Distinct().Count()
                }
            ).ToList().Select(s => new CitysWithComplaintsall
            {
                CityId = s.RId,
                City_NM = s.RName,
                Num_Complaints_Agency = s.IndividualCount,
                Num_Complaints_Ind = s.AgencyCount
            }).ToList();

我想在各处添加左联接,而不是简单联接。

在SQL Server中具有左联接的相同查询如下:

select 
    R.region_id, R.region_name, 
    count(IR.Id) as Individual, 
    count(AR.Id) as Agency 
from 
    region R 
left join 
    governorate G on r.region_id = g.region_id
left join 
    IndividualReports IR on g.governorate_id = IR.governorate_id
left join 
    AgencyReports AR on g.governorate_id = AR.governorate_id
group by 
    R.region_id, R.region_name

另一件事是,如果我尝试更改此查询以检查计数,将原始SQL查询返回一些不同的结果,则将其更改为:

select  
    R.region_id, R.region_name,
    count(AR.Id) as Agency 
from 
    region R 
left join 
    governorate G on r.region_id = g.region_id
left join 
    AgencyReports AR on g.governorate_id = AR.governorate_id
group by 
    R.region_id, R.region_name

SQL查询返回的结果略有不同。

0 个答案:

没有答案