[英]Entity Framework many-to-many relation. Stock of a product in a warehouse
So right now i'm coding a product selection tool for a sales module and i want to show the stock of each product selected for the sale. 所以现在我正在为销售模块编写产品选择工具,我想显示为销售选择的每种产品的库存。 I have two tables: Products and Warehouses and a table that has a relation between them and the stock of a product in a warehouse. 我有两个表:产品和仓库以及一个表,它们与仓库中的产品库存有关系。
A query for this would be something along the lines of 对此的查询将是类似的
productsXwarehouses pxw = dbGateway.productsXwarehouses
.Where(item => item.idproduct=idproduct && item.idWarehouse==idWarehouse).First();
But i would have to do this for each row of the table and it seems really inneficient. 但是我必须为表格的每一行做这个,看起来真的很有用。 I was wondering if maybe there is a better aproach. 我想知道是否有更好的方法。 Thanks! 谢谢!
Thanks! 谢谢!
Try this: 尝试这个:
var stock =
from pw in dbGateway.productsXwarehouses
group pw.Product by pw into g
select new
{
Product = g.Key,
TotalStock = g.Sum(w => w.Stock)
};
I'm assuming that your productsXwarehouses
table has a Stock
column of type int
. 我假设您的productsXwarehouses
表有一个int
类型的Stock
列。
But perhaps an even nicer solution is this: 但也许更好的解决方案是:
var stock =
from product in dbGateway.Products
select new
{
Product = product,
TotalStock = product.productsXwarehouses.Sum(w => w.Stock)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.