1
IQueryable<Appeal> appeal = Repository.Appeals.Include("Case").Include("Case.Patient").Include("ShipmentAppeals").Where(ap => ap.CaseId == caseID);

IQueryable<ICollection<ShipmentAppeals>> shipmentAppeals = appeal.Select(ap => ap.ShipmentAppeals)

ShipmentAppeals 是 Appeal 和 Shipment 实体之间的关联表。

我想从 Repository.Shipments 中获取那些 ShipmentID 存在于上述 shippingAppeals 集合中的货物。

我写的查询如下。它确实有效,但我想避免 for each 循环:

 foreach (ICollection<ShipmentAppeals> sAppealOuter in shipmentAppeals.ToList())
        {
            foreach (ShipmentAppeals sAppealInner in sAppealOuter)
            {
                Shipment shipment = Repository.Shipments.First(s => s.ID == sAppealInner.ShipmentID);
                    caseShipments.Add(shipment);
                }
            }

        }
4

1 回答 1

2

首先,我们可以使用SelectMany将一系列上诉集合转换为上诉。

接下来,我们可以只使用一个查询来获取所有上诉的所有货物,而不是遍历它们中的每一个并进行数据库查询来获取货物。这可以通过Join. (或者,如果有您不想要的重复货件,您可以使用 aGroupJoin并选择每个组中的第一项。)

var caseShipments = shipmentAppeals.SelectMany(repository => repository)
    .Join(Repository.Shipments, appeal => appeal.ShipmentID
        , shipment => shipment.ID, (appeal, shipment) => shipment);

或者在查询语法中:

var caseShipments = from repository in shipmentAppeals
                    from appeal in repository
                    join shipment in Repository.Shipments
                    on appeal.ShipmentID equals shipment.ID
                    select shipment;

请注意,由于延迟执行,整个查询只会进行一次数据库往返,因为每个查询都用于组合另一个查询,而不是首先执行。

于 2013-10-28T14:57:50.210 回答