我如何轉換這個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
我如何轉換這個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
讓我們假設YourContext
產生上下文和導航屬性之間的tbl_Period
和tbl_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 ...
}
請檢查
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();
錯誤已接近「選擇」 – user3458120
請嚐嚐我更新的查詢發生........ –
嘗試用這種
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你必須改變listPeriod
和listSample
用正確的集合(或表實體)
發表您的實體。 – Ehsan
http://www.linqpad.net/約瑟夫阿爾巴哈利和Ben阿爾巴哈利是好朋友 – Artru