分组依据并求和多列

时间:2019-07-03 05:59:07

标签: c# sql linq lambda

我有以下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; }        
    } 


}

1 个答案:

答案 0 :(得分:2)

很可能您正在获取Categorynull的数据。因此,您需要在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);