在实体框架中添加where到SUM
本文关键字:where SUM 添加 实体 框架 | 更新日期: 2023-09-27 18:15:08
我有一个EF查询:
var result = unitOfWork.deviceInstanceRepository.Get()
.GroupBy(w => new
{
DeviceId = w.DeviceId,
CatalogName = w.Device.CatalogNo,
DeviceName = w.Device.Name,
ManufacturerName = w.Device.Manufacturer1.Name,
})
.Select(s => new InstancesSummary
{
DeviceId = s.Key.DeviceId,
CatalogNo = s.Key.CatalogName,
DeviceName = s.Key.DeviceName,
DeviceManufacturer = s.Key.ManufacturerName,
Quantity = s.Sum(x => x.Quantity)
}).ToList();
目前,它返回一个不同的对象列表,其中包含来自数据库的Count
。但是我想修改这个查询以获得与eg连接的设备的数量。用户1和用户2
我知道我可以这样做:
List<Expression<Func<DeviceInstance, bool>>> where = new List<Expression<Func<DeviceInstance, bool>>>();
where.Add(w => w.DeviceUsage.UserId == 1);
为用户1,并更改这一行:
var result = unitOfWork.deviceInstanceRepository.Get(where)
但是在这个解决方案中,我需要进行两个查询。
有没有办法做出这样的东西:
Quantity = s.Sum(x => x.Quantity).Where(w=>w.DeviceUsage.UserId==1)
获取与用户1和用户2连接的设备总数?
@更新DevinceInstance
类:
public partial class DeviceInstance
{
public int Id { get; set; }
public int DeviceId { get; set; }
public string SerialNo { get; set; }
public System.DateTime CreationDate { get; set; }
public Nullable<int> ProjectId { get; set; }
public bool Issue { get; set; }
public string IssueDetails { get; set; }
public int Quantity { get; set; }
public virtual Device Device { get; set; }
public virtual Project Project { get; set; }
public virtual DeviceUsage DeviceUsage { get; set; }
}
你可以试试这个:
Quantity = s.Where(w=>w.DeviceUsage.UserId==1 || w.DeviceUsage.UserId==2)
.Sum(x => x.Quantity);