我想要数据库表中具有相同项ID的所有行中的所有商品价格的总和。我的意思是当我从下拉列表中选择特定的项目ID时,结果应该是一个数字并自动将其放在文本框中
我怎样才能在linq中完成?
public double oIlstGetVouchersDetailjh(int nvoucherID)
{
Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
double sum = (from Entity in sNairoukhEntities1.INV_InventoryItems
where Entity.ItemID == nvoucherID
select Entity.ItemPrice).sum();
return sum;
}
或
public double oIlstGetVouchersDetailjh(int nvoucherID)
{
Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
double olstInvoicesSrech = from Entity in sNairoukhEntities1.INV_InventoryItems
group Entity by Entity.ItemID == nvoucherID into g
select g.sum(Entity => Entity.ItemPrice);
return olstInvoicesSrech;
}
但第二个查询给我这个msg无法隐式转换类型'System.Linq.IQueryable'为'double
答案 0 :(得分:1)
在您的情况下,这将有效:
Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
double sum = (from Entity in sNairoukhEntities1.INV_InventoryItems
where Entity.ItemID == nvoucherID
select Entity.ItemPrice).Sum(); // Change sum to Sum
return sum;
这是一种更简单的方法:
sNairoukhEntities1.INV_InventoryItems.Where(item => item.ItemID == nvoucherID).Sum(item => item.ItemPrice);