我正在开发asp.net核心应用程序。我有以下linq查询,用于填充模型。此模型具有属性qtryregions,这是一个列表。如何在一个查询中填写它。
keras
我不想使用上面的foreach并希望在第一个linq查询中填充product.Qtyregion。
请建议。
答案 0 :(得分:0)
这是你想要的吗?
Products = (
from d in db.PODetails
join p in db.Products on d.ProductID equals p.ProductID
where d.POID == id
select new PODetailsFull
{
PODetailID = d.PODetailID,
//QtyRegion = new List<string>() { Region.Region + " " + POAllocation.Allocate != null ? POAllocation.Allocate.ToString() : "" },
Sku = p.Sku,
Cntnr20 = p.Cntnr20 ?? 0,
Cntnr40 = p.Cntnr40 ?? 0,
Cntnr40HQ = p.Cntnr40HQ ?? 0,
QtyRegion = (
from POAllocation in db.POAllocations.Where(p => p.PODetailID == d.PODetailID)
join regions in db.Regions on POAllocation.RegionID equals regions.RegionID
select regions.Region + " " + POAllocation.Allocate ?? "").ToList(),
}).ToList();
答案 1 :(得分:0)
尝试使用分组依据来避免N + 1查询问题:
Products = (
from d in db.PODetails
join p in db.Products on d.ProductID equals p.ProductID
join palloc in db.POAllocations on d.PODetailID equals palloc.PODetailID
group by new {
PODetailID = d.PODetailID,
Sku = p.Sku,
Cntnr20 = p.Cntnr20,
Cntnr40 = p.Cntnr40,
Cntnr40HQ = p.Cntnr40HQ }
into grp
where grp.Key.POID == id
select new PODetailsFull
{
PODetailID = grp.Key.PODetailID,
QtyRegion = grp,
Sku = grp.Key.Sku,
Cntnr20 = grp.Key.Cntnr20 ?? 0,
Cntnr40 = grp.Key.Cntnr40 ?? 0,
Cntnr40HQ = grp.Key.Cntnr40HQ ?? 0
}).ToList();