[英]Group By & Sum Multiple Columns
我有以下sql查詢,我想將其轉換為lambda表達式:
SELECT TOP 10 SUM(Quantity * Price) AS Quantity, Category
FROM InvoiceItem
WHERE Unit = 'Hour'
GROUP BY Category
ORDER BY Quantity DESC
我已經嘗試了很多事情,但是我不明白這是怎么回事:
var data = _db.InvoiceItem.Where(where => where.Unit == "Hour")
.GroupBy(group => new { group.Category })
.Select(group => new
{
Category = group.Key.Category,
Quantity = group.Sum(s => s.Quantity * s.Price)
})
.OrderByDescending(ob => ob.Quantity)
.Take(10);
不幸的是,我一直收到以下錯誤:
Message =“數據為Null。不能在Null值上調用此方法或屬性。”
這是我的模型:
namespace Accounts.Models
{
public enum UnitList
{
Hour, Each, Km, Bag
}
public class InvoiceItem
{
public InvoiceItem()
{
Price = 0;
Quantity = 1;
Unit = UnitList.Each.ToString();
Display = false;
}
[Key]
public int InvoiceItemID { get; set; }
[Required]
public int InvoiceID { get; set; }
[Required]
public int PersonID { get; set; }
[Required]
public Guid UserID { get; set; }
[Required]
[DataType(DataType.Date)]
//[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date { get; set; }
[StringLength(50)]
public string Category { get; set; }
[StringLength(50)]
public string Aircraft { get; set; }
[Required]
[StringLength(200)]
public string Description { get; set; }
[Required]
[StringLength(20)]
public string Unit { get; set; }
[Required]
[DataType(DataType.Currency)]
[DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:c}")]
public decimal Price { get; set; }
[Required]
[DefaultValue(1)]
public decimal? Quantity { get; set; }
[UIHint("Boolean")]
public Boolean Display { get; set; }
public virtual Invoice Invoice { get; set; }
public virtual Person Person { get; set; }
}
}
最有可能您正在獲取Category
為null
數據。 因此,您需要在Where
添加額外條件。 另外,您可以稍微簡化GroupBy
:
_db.InvoiceItem.Where(i => i.Unit == "Hour" && i.Category != null)
.GroupBy(i => i.Category)
.Select(i => new
{
Category = i.Key.Category,
Quantity = i.Sum(s => s.Quantity * s.Price)
})
.OrderByDescending(i => i.Quantity)
.Take(10);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.