[英]How sum a column in Entity Framework using linq and join it with another table
說這可能是較短的版本有點模糊:
var result = transactions
.Join(goodbBrands,
tr => tr.GoodsID,
gb => gb.GoodsID,
((transaction, brand) => new
{
transaction,
brand
}))
.Join(goods,
gbs => gbs.transaction.GoodsID,
g => g.ID,
(gbs, good) => new
{
Brand = gbs.brand,
Transaction = gbs.transaction,
Good = good
})
.Join(brands,
gb => gb.Brand.BrandID,
b => b.ID,
((gbs, brds) => new
{
Brand = brds,
Good = gbs.Good,
Transaction = gbs.Transaction
})).Select(item => new
{
GoodsName = item.Good.Name,
Brand = item.Brand.Name,
Qty = item.Transaction.Quantity
});
但實際上,使用 Entity Framework Navigation Properties和Include
forLoading Related Data為表創建正確的 model 關系會好得多。
這樣上面的大規模查詢就可以變得簡單得多:
var res = transactions.Include(tr => brands)
.Include(tr => goods)
.Select( ... );
要選擇數量,您應該能夠:
firstTable.Where(x => x.Input).GroupBy(x => x.GoodsID).Select(x => x.Sum(y => y.Quantity));
我將把連接留作練習,因為它有據可查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.