我有两张桌子:
产品和库存
我目前选择产品的内容并对库存表进行第二次调用,以总结产品ID的总库存量,这非常慢。
我想要的是创建对数据库的单个调用以获取Product表的内容,并将stock表中的StockInHand总和(链接到ProductID)的总和如下所示:
如果有人可以告诉我如何成功加入表格并在同一个ProductID的调用中将Stock表的QtyInHand相加,我会非常感激。
我的原始代码:
var query = from products in data.Products
where products.Deleted == false
orderby products.FullPath
select new
{
ProductID = products.ProductID,
Description = products.Description,
Price = products.RetailPrice ?? 0,
>>>> VERY SLOW! StockLevel = cProducts.GetStockTotalForProduct(products.ProductID),
FullPath = products.FullPath
};
if (query != null)
{
dgv.DataSource = query;
}
我理解我需要加入表格,但我不确定使用LINQ执行此操作的语法:
var query =
from product in data.Products
join stock in data.ProductStocks on product.ProductID equals stock.ProductID
DO SOMETHING CLEVER HERE!!
select new
{
ProductID = product.ProductID,
Description = product.Description,
Price = product.RetailPrice ?? 0,
StockLevel = >>>>>>>> CALL TO THE OTHER TABLE IS VERY SLOW,
FullPath = products.FullPath
};
if (query != null)
{
dgv.DataSource = query;
}
答案 0 :(得分:1)
我认为这应该有效:
var query = from product in data.Products
join stock in data.ProductStocks on product.ProductID equals stock.ProductID
select new
{
ProductID = product.ProductID,
Description = product.Description,
Price = product.RetailPrice ?? 0,
StockLevel = stock.StockLevel,
FullPath = products.FullPath
};
答案 1 :(得分:1)
我认为你正在寻找group by
来做总和:
var query = from p in data.Products
join s in data.ProductStocks on p.ProductID equals s.ProductID
group s by p into g
select new {
ProductID = g.Key.ProductID,
Description = g.Key.Description,
Price = g.Key.Price ?? 0,
FullPath = g.Key.FullPath,
StockLevel = g.Sum(s => s.StockInHand)
};