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&amp;的关联表。装运实体。
我想从Repository.Shipments中获取那些货件,其ShipmentID存在于以上的shipmentAppeals集合中。
我写的查询如下。它确实有效,但我想避免每个循环:
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);
}
}
}
答案 0 :(得分:2)
首先,我们可以使用SelectMany
将一系列上诉集合转换为上诉。
接下来,我们可以只使用一个查询来获取所有上诉的所有货件,而不是通过它们中的每一个并进行数据库查询以获得货件。这可以通过Join
来完成。 (或者,如果您不想要重复发货,可以使用GroupJoin
并选择每个组中的第一个项目。)
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;
请注意,由于延迟执行,此整个查询将只进行一次数据库往返,因为每个查询都用于组成另一个查询,而不是先执行。