我有一個產品的銷售資料,想顯示按產品ID分組的銷售摘要。 總結結果應該顯示產品名稱和總銷售額。我怎樣才能在groupby結果中選擇一個欄位,并且該欄位不是關鍵欄位。
public partial class SaleOrderDetail
{
public int Id { get; set; }
public int ProductId { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
public decimal LineTotal { get; set; }
}
var query = from saleorder in _dbContext.SaleOrderDetail
group saleorder by saleorder.ProductId into salesummary
select new
{
productid = salesummary.Key,
prdouctname = salesummary.First().ProductName,
totalqty = salesummary.Sum(s => s.Quantity)
};
我得到的錯誤是invalidoperationException,因為First()的產品名稱。
uj5u.com熱心網友回復:
你必須在分組鍵中包含ProductName。
var查詢 =
from saleorder in _dbContext.SaleOrderDetail
group saleorder by new {saleorder.ProductId, saleorder.ProductName} into salesummary
selectnew
{
productid = salesummary.Key.ProductId,
prdouctname = salesummary.Key.ProductName,
totalqty = salesummary.Sum(s => s.Quantity)
};
uj5u.com熱心網友回復:
將SaleOrderDetail設為AsEnumerable()就可以了。對于SQL運算式,如果把它作為AsEnumerable()或.ToList<>等,它將會起作用。
var query = from saleorder in _dbContext.SaleOrderDetail.AsEnumerable()
group saleorder by saleorder.ProductId into salesummary
select new
{
productid = salesummary.Key,
prdouctname = salesummary.First().ProductName,
totalqty = salesummary.Sum(s => s.Quantity)
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/310095.html
標籤:
上一篇:如何用Linq過濾子物體?
下一篇:ChoETL嵌套JSON到CSV
