2014-06-27 40 views
1

我想這兩個LINQ查詢合併爲1:的LINQ集團與SUM不同表中同一列

var query = from s in _context.Set<StockInventoryItem>() 
         where s.StockCatalogueItemId == id 
         group s by s.StockType into g 
         select new 
         { 
          inStock = g.Sum(x => x.QtyInStock), 
         }; 

     var query2 = from p in _context.Set<PurchaseOrderItem>() 
        where p.StockCatalogueItemId == id 
        group p by p.StockType into g2 
        select new 
        { 
         onOrder = g2.Sum(x => x.QtyStillDue) 
        }; 

注意,過濾,分組和輸出兩個表是相同的,我希望結果是這樣的:

StockType inStock onOrder 
+----------+--------+--------+ 
    Type 1  4  3 
+----------+--------+--------+ 
    Type 2  0  1 

即由數量StockType

分組這是EF代碼第一,有這些表之間沒有直接的關係,我這就是爲什麼我在服務層嘗試這個查詢,所以我可以訪問這兩個實體。

回答

1

你應該能夠兩組「鞋拔子」與匿名類型和Concat相同的序列,然後分別統計的結果,就像這樣:

var query = _context.Set<StockInventoryItem>() 
    .Where(ii => ii.StockCatalogueItemId == id) 
    .Select(ii => new { 
     II = ii, PO = (PurchaseOrderItem)null 
    }).Concat(_context.Set<PurchaseOrderItem>() 
    .Where(po => po.StockCatalogueItemId == id) 
    .Select(po => new { 
     II = (StockInventoryItem)null, PO = po 
    })).GroupBy(p => II != null ? ii.StockType : PO.StockType) 
    .Select(g => new { 
     InStock = g.Sum(p => p.II != null ? p.II.QtyInStock : 0) 
    , OnOrder = g.Sum(p => p.PO != null ? p.PO.QtyStillDue: 0) 
    });