我有一个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
的对象的不同列表。但我想修改此查询以获取与例如连接的设备数量。用户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相同的设备总数?
@Updated with DevinceInstance
class:
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; }
}
答案 0 :(得分:1)
你可以尝试这个:
Quantity = s.Where(w=>w.DeviceUsage.UserId==1 || w.DeviceUsage.UserId==2)
.Sum(x => x.Quantity);