public class Inventory
{
public int Id { get; set; }
public int ProductId { get; set; }
public int LocationId { get; set; }
public int Quantity { get; set; }
public decimal PurchasePrice { get; set; }
public decimal ResellerPrice { get; set; }
public decimal RetailPrice { get; set; }
public byte FundSource { get; set; }
public string Note { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateUpdated { get; set; }
public Product Product { get; set; }
public Location Location { get; set; }
}
public class InventoryEvent
{
public int Id { get; set; }
public int ProductId { get; set; }
public int LocationId { get; set; }
public int Quantity { get; set; }
public decimal? Price { get; set; }
public decimal? Total { get; set; }
public byte EventType { get; set; }
public byte? PaymentMethod { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateUpdated { get; set; }
public virtual Product Product { get; set; }
public virtual Location Location { get; set; }
}
如何在LINQ中做到这一点,
select A.Id, sum(A.Quantity) as totalQuantity,
(totalQuantity -
(select sum(B.Quantity)
from InventoryEvent B
where B.ProductId = A.ProductId and B.LocationId = A.LocationId
group by B.ProductId, B.LocationId)
) as Available
from Inventory A
group by A.ProductId, A.LocationId
在按ProductId
和LocationId
分组后,我想在库存A中显示各列,并附加2列; sum(A.Quantity)
和(sum(A.Quantity) - sum(B.Quantity))
并同时渴望加载A.Product
和A.Location
我尝试过
var inventories = AppContext.Inventories.Include(i => i.Product)
.Include(i => i.Location)
.GroupBy(i => new { i.LocationId, i.ProductId });
但是我不知道该如何前进,甚至不确定它是否正确。
答案 0 :(得分:0)
如果要选择SUM,则无法显示单个对象的ID。
您可以显示ProductId和LocationId(要分组的列)。
如果仅引用ProductId和LocationId,我不确定是否需要包含产品或位置。
尝试类似的方法(未经测试):
var inventories = AppContext.Inventories.GroupBy(x => new { x.ProductId, x.LocationId }).Select(g => new
{
g.Key.ProductId,
g.Key.LocationId,
totalQuantity = g.Sum(y => y.Quantity),
Available = g.Sum(y => y.Quantity) - AppContext.InventoryEvents.Where(e => e.ProductId == g.Key.ProductId && e.LocationId == g.Key.LocationId).Sum(x => x.Quantity)
});