如何将SUM聚合函数添加到Entity Framework查询中

时间:2014-04-08 09:30:17

标签: c# entity-framework

我有一个问题:

var resultb = unitOfWork.deviceInstanceRepository.Get()
            .Select(s => new
            {
                DeviceId = s.DeviceId,
                Name = s.Device.Name,
                Manufacturer = s.Device.Manufacturer1.Name,
                Quantity = s.Quantity
            })
            .GroupBy(w => new
            {
                w.DeviceId,
                w.Name,
                w.Manufacturer,
                w.Quantity
            }).ToList();

我想改变这一行: Quantity= s.Quantity

进入

Quantity=Sum(s=>s.Quantity)

我找到了Click 但实现这一点仍然存在一些问题。 Intellisense中没有Sum方法。

当我更改SelectGroupBy的地点时

var resultb = unitOfWork.deviceInstanceRepository.Get()
            .GroupBy(w => new
            {
                w.DeviceId,
                w.Device.Name,
                w.Device.Manufacturer,
                w.Quantity
            })
            .Select(s => new
            {
                DeviceId = s.DeviceId,
                Name = s.Device.Name,
                Manufacturer = s.Device.Manufacturer1.Name,
                Quantity = s.Sum(s=>s.Quantity)
            })

我可以使用Sum,但是像s.DeviceId这样的行会引发Anonymous type does not contain definition of deviceId错误。 s.Device.Names>device.Manufacuter1.Name

的错误相同

1 个答案:

答案 0 :(得分:5)

您必须在没有Quantity属性的情况下进行分组,因为这是您要在分组中聚合的属性:

unitOfWork.deviceInstanceRepository.Get()
          .GroupBy(w => new
          {
              DeviceId = w.DeviceId,
              Device = w.Device.Name,
              Manufacturer = w.Device.Manufacturer,
          })
          .Select(s => new
          {
              DeviceId = s.Key.DeviceId,
              Name = s.Key.Device,
              Manufacturer = s.Key.Manufacturer.Name,
              Quantity = s.Sum(x => x.Quantity)
          })