如何在Linq扩展中对孩子的孩子的值进行求和

时间:2013-03-28 05:05:44

标签: linq c#-4.0 entity-framework-5

我有这样的相关表结构:

enter image description here

给定WorkReleaseDetail.WorkReleaseHeaderId,我希望使用Linq扩展来获取WorkOrderDetail.ItemId分组的WorkOrderDetail.EstimatedQty的总和。

由于我需要将最下面的表分组,我以为我能够。在哪里:

WorkOrderDetail.WorkOrderHeader.WorkReleaseDetail.WorkReleaseHeaderId == id

但是当你在OrderGroupDetails停止时没有骰子,因为它是一个聚合,你唯一的选择是.Sum等,这是有道理的。

然后我想这样做(这应该有效):

var woDtlRepos = new Repository<WorkOrderDetail>();
var workOrdDtl = woDtlRepos.SearchFor(
x => x.WorkOrderHeader.FacilityId == intFacilityId
&& x.WorkOrderHeader.WorkReleaseDetails.WorkOrderHeaderId == intWorkReleaseId);

var workRlsNeeds = workOrdDtl
.GroupBy(group => new
    {
        group.ItemId
    }
)
.Select(result => new 
    { 
        ItemId = result.Key.ItemId,
        TotalQty = result.Sum(a => a.EstimatedQuantity)
    }
);

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

啊......顿悟......用.Any()

var workOrdDtl = woDtlRepos.SearchFor(
x => x.WorkOrderHeader.FacilityId == intFacilityId
&& x.WorkOrderHeader.WorkReleaseDetails.Any(woRlsHdr => woRlsHdr.WorkReleaseHeaderId ==      intWorkReleaseId));