2014-03-27 166 views
-1

我如何轉換這個SQL查詢來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,計數,PeriodID

+0

發表您的實體。 – Ehsan

+0

http://www.linqpad.net/約瑟夫阿爾巴哈利和Ben阿爾巴哈利是好朋友 – Artru

回答

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 ... 
    } 
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(); 
+0

錯誤已接近「選擇」 – user3458120

+0

請嚐嚐我更新的查詢發生........ –

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用正確的集合(或表實體)