尝试将简单的SQL查询编写为LINQ。
这是SQL:
SELECT p.id, p.customer, SUM(pd.total_price)
FROM purchases p JOIN purchases_details pd ON p.id = pd.purchase_id
GROUP BY pd.purchase_id
到目前为止我最好的LINQ:
var purchases_with_details = from p in db.Purchases
join pd in db.Purchases_details on p.Id equals pd.purchase_id
group pd by pd.purchase_id into pdg
select new { ??? };
问题是我只能在pdg.*
中写select new { }
。
我想写一些类似{ p.id, p.customer, pdg.Sum(o => o.total_price) }
任何人都知道怎么做?
答案 0 :(得分:1)
尝试:
var purchases_with_details = from pd in db.Purchases_details
group pd by pd.purchase_id into pdg
//join *after* group
join p in db.Purchases on pdg.Key equals p.Id
select new
{
Id = p.Id,
Cust =p.customer,
TotalPrice = pdg.Sum(y => y.total_price)
};
答案 1 :(得分:0)
你可以尝试这个
var purchases_with_details = from p in db.Purchases
join pd in db.Purchases_details on p.Id equals pd.purchase_id
group pd by pd.purchase_id into pdg
select new {
PurchaseID=pdg.Key.purchase_id,
TOTAL=pdg.Sum(x=>x.total_price)
};