什么是db join with group by的linq等效项

时间:2019-04-30 11:20:07

标签: c# sql linq

什么是linq等效于以下查询:

SELECT
   h.State,COUNT(p.NPRID)
   FROM PopulationRegistrationEntity p
   INNER JOIN HouseListingEntity h
   ON h.CensusHouseNoID = p.CensusHouseNoID
   GROUP BY h.State    

我已经尝试过,但是没有用:

var a = (from h in db.HouseListingEntity
                     join p in db.PopulationRegistrationEntity on h.CensusHouseNoID equals p.CensusHouseNoID
                     group p by new { h.State } into g
                     select new { State = g.Key.State, Count = g.Count(p1 => p1.NPRID > 0) });

1 个答案:

答案 0 :(得分:3)

h而不是p

var a = (from h in db.HouseListingEntity
         join p in db.PopulationRegistrationEntity on h.CensusHouseNoID equals p.CensusHouseNoID
         group h by h.State into g
         select new { State = g.Key.State, Count = g.Count(p1 => p1.NPRID > 0) });
  

在g.Key.State和p1.NPRID的最后一行代码中显示编译时错误

使用let子句:

var a = (from h in db.HouseListingEntity
         join p in db.PopulationRegistrationEntity on h.CensusHouseNoID equals p.CensusHouseNoID
         let temp = new { HouseListingEntity = h, PopulationRegistrationEntity = p }
         group temp by temp.HouseListingEntity.State into g
         select new { State = g.Key, Count = g.Count(p1 => p1.PopulationRegistrationEntity.NPRID > 0) });