【发布时间】:2018-07-19 12:06:04
【问题描述】:
我正在尝试使用左联接从 2 个表中获取数据到嵌套查询。这使我可以从 Item 表中获取数据,但不能从购物车(嵌套查询)表中获取数据:
var q = from s in db.Items
join sub in (from c in db.Carts
where c.CartID == 1
group c by c.ItemID into g
select new
{
ItemID = g.Key,
Qty = g.Select(s => s.Qty)
}) on s.ItemID equals sub.ItemID into a
select new ItemViewModel
{
CategoryID = s.CategoryID,
Description = s.Description,
Price = s.Price,
**This being the issue------>>>>>>>** //Qty = a.Select(j => j.Qty),
ItemID = s.ItemID,
ItemName = s.ItemName
};
viewModel = q.ToList();
我想要达到的查询是:
select Items.*, Cart.Qty
from Items
left join (select ItemID, Qty from carts where CartID = 1 ) Cart
on Items.ItemID = Cart.ItemID
【问题讨论】:
-
重要的是,
ItemViewModel.Qty属性的类型是什么? -
属性设置为 int,但给出的错误是无法将 system.Collections.Generic.IEnumberable
转换为 int。 -
Select总是返回一个集合。如果要将其折叠成单个值,则需要使用适当的折叠函数:Count、Sum、Aggregate等。
标签: c# asp.net-mvc entity-framework linq lambda