2017-08-03 24 views
-1

私はasp.netコアアプリケーションで作業しています。私はモデルを埋めるために使用されているlinqのクエリを次のとおりです。このモデルにはリストであるプロパティqtryregionsがあります。 1つのクエリでどのように記入することができますか。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を使いたくなく、product.Qtyregionを最初のlinqクエリに使用したくありません。

お勧めします。

答えて

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