C# 如何使用实体框架LINQ获取列和
我想使用LINQ获得列“Weight”的和,并存储在列表中。以下是两列联接操作的代码C# 如何使用实体框架LINQ获取列和,c#,entity-framework,linq,C#,Entity Framework,Linq,我想使用LINQ获得列“Weight”的和,并存储在列表中。以下是两列联接操作的代码 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 })
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的变量中(并且您希望得到由所有其他字段的不同组合组成的组的权重之和):
在你的代码末尾附加这个
.Groupby(w=>w.Weight).Convert(g=>g.Sum())
在我看来,结构
和订单计划
之间有一对多的关系:每个结构
都有零个或多个订单计划
,每个订单计划
只属于一个结构
,即外键所指的结构
在我看来,您需要几个Fabric
属性及其OrderPlans
的(几个属性)以及这些OrderPlans
的总重量
当您有一对多关系或多对多关系,并且希望获取“项目及其子项目”,例如学校及其学生、客户及其订单或订单及其订单行时,您可以使用而不是标准联接
// 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(),
});
您需要先应用group by,然后才能使用Sum运算符。@sriharsha您能对该代码进行注释吗?
// 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(),
});