![](/img/trans.png)
[英]How sum a column in Entity Framework using linq and join it with another table
[英]How to get SUM of column using Entity Framework LINQ
我想使用LINQ獲取“重量”列的SUM並存儲在列表中。 以下是兩列的聯接操作代碼。
var que = (from o in db.OrderPlans.Where(i => i.DemandId == _demandId)
join f in db.Fabrics
on o.FabricId equals f.Id
select new
{
f.Id,
f.Name,
o.Width,
f.Type,
o.GSM,
o.Weight
}).ToList();
假設您上面發布的代碼有效,並且假設您將其存儲在一個名為joinedList的變量中(並且您希望將由所有其他字段的不同組合形成的組的權重之和):
var groupedList = joinedList.GroupBy(grp => new {
grp.Id,
grp.Name,
grp.Width,
grp.Type,
grp.GSM
}).Select(grp => new {
grp.Key.Id,
grp.Key.Name,
grp.Key.Width,
grp.Key.Type,
grp.Key.GSM,
SumOfWeight = grp.Sum(w => w.Weight)
}).ToList();
在您的代碼末尾附加此.Groupby(w => w.Weight).Convert< int >(g=> g.Sum());
在我看來, Fabric
和OrderPlan
之間存在一對多的關系:每個Fabric
具有零個或多個OrderPlans
,每個OrderPlan
完全屬於一個Fabric
,即外鍵引用的Fabric
。
在我看來,您想要具有其OrderPlans
(的幾個屬性)和這些OrderPlans
的總權重的幾個Fabric
屬性。
每當您具有一對多關系或多對多關系並且想要獲取“帶有子項的項目”時,例如學校與學生,客戶與訂單或訂單與訂單行,例如使用Queryable.GroupJoin而不是標准聯接 。
// GroupJoin Fabrics with some of their OrderPlans:
var result = dbContext.Fabrics
.GroupJoin(dbContext.OrderPlans.Where(orderPlan => ...)
fabric => fabric.Id, // from each Fabric take the primary key
orderPlan => orderPlan.FabricId, // from each OrderPlan take the foreign key
// ResultSelector: take every Fabric with all his matching OrderPlans to make one new object:
(fabric, orderPlansOfthisFabric) => new
{
// Select the Fabric properties you want
Id = fabric.Id,
Name = fabric.Name,
Type = fabric.Type,
OrderPlans = orderPlansOfThisFabric.Select(orderPlan => new
{
// Select the OrderPlan properties you want:
Width = orderPlan.Width,
Gsm = orderPlan.Gsm,
}
// Weight: calculate the sum of all OrderPlans of this Fabric:
Weight = orderPlansOfThisFabric
.Select(orderPlan => orderPlan.Weight)
.Sum(),
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.