Linq GROUP & SUM the same columns from different tables -
i'm trying combine these 2 linq queries 1:
var query = s in _context.set<stockinventoryitem>() s.stockcatalogueitemid == id group s s.stocktype g select new { instock = g.sum(x => x.qtyinstock), }; var query2 = p in _context.set<purchaseorderitem>() p.stockcatalogueitemid == id group p p.stocktype g2 select new { onorder = g2.sum(x => x.qtystilldue) };
note filtering, grouping , output same both tables, , want results this:
stocktype instock onorder +----------+--------+--------+ type 1 4 3 +----------+--------+--------+ type 2 0 1
i.e. quantities grouped stocktype
this ef code first , there no direct relationship between these tables, why i'm trying query in service layer can access both entities.
you should able "shoehorn" both groups same sequence anonymous types , concat
, , count results separately, this:
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) });
Comments
Post a Comment