![](/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.