2017-08-03 123 views
-1

我正在研究asp.net核心应用程序。我有下面的linq查询是用来填充模型。这个模型有一个属性qtryregions这是一个列表。我怎样才能填写一个查询。如何在C#中使用linq填充模型列表

public JsonResult PODetailsList(int id) 
    { 
     List<PODetailsFull> Products; 
     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, 
     }).ToList(); 


     foreach (var product in Products) 
     { 
      var result = (from POAllocation in db.POAllocations.Where(p => p.PODetailID == product.PODetailID) 
          join regions in db.Regions on POAllocation.RegionID equals regions.RegionID 
          select regions.Region + " " + POAllocation.Allocate ?? "" 
     ).ToList(); 

      product.QtyRegion = result; 
     } 

     return Json(new { data = Products }, JsonRequestBehavior.AllowGet); 
    } 

我不想使用上面的foreach并希望在第一个linq查询中填充product.Qtyregion。

请建议。

回答

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(); 
+0

这是造成异常。 –

+0

@AsifHameed - 然后您需要将记录拉入内存并在那里进行最终查询。 – Enigmativity

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();