将此连接sql查询转换为linq

时间:2014-03-27 07:08:55

标签: c# asp.net linq

如何将此sql查询转换为linq

 select sum(a.Count),b.PeriodDesc from dbo.tbl_Sample a,dbo.tbl_Period b 
 where a.PeriodID=b.PeriodID group by PeriodDesc 

tbl_Period -PeriodID,PeriodDesc
tbl_Sample - ID,Count,PeriodID

3 个答案:

答案 0 :(得分:0)

我们假设YourContext是生成的上下文,并且您在tbl_Periodtbl_Sample之间有导航属性,而查询将如下所示:

   using(var db = new YourContext())
   {
          var result = db.tbl_Sample.GroupBy(p=>p.tbl_Period.PeriodDesc)
          .Select(p => new {p.Key, p.Count()})
          //whateve you want to do ...
   }

答案 1 :(得分:0)

请检查

var result = (from a in tbl_Sample
group a by a.PeriodDesc into abc                         
join b in tbl_Period on abc.FirstOrDefault().PeriodID equals b.PeriodID    
 select new ModelName {
   SumofCount = abc.sum(m => m.Count), 

   PeriodDesc = b.PeriodDesc 
 }).tolist();

答案 2 :(得分:0)

试试这个

var joinedTables = from p in listPeriod
join s in listSample on p.PeriodID equals s.PeriodID
select new { p.PeriodDesc, s.Count };

var result = from p in joinedTables
group p by p.PeriodDesc into g
select new { PeriodDesc = g.Key, Sum = g.Sum(p=>p.Count)};

Ofc你必须用正确的集合(或表格实体)更改listPeriodlistSample