2017-08-03 120 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();