>我有 2 个列表。购物车列表,其中包含具有属性的对象; Quantity
和ProductId
.然后,我从购物车列表中ProductId
存储库(IQueryable
)获取所有产品。这意味着对于每个产品,都有一个购物车对象,其中包含与之相关的Quantity
。
在进行选择时,我也想分配此Quantity
,但我知道这样做的唯一方法是再次查询购物车。
对于 egx。
model = (from p in productService.GetAllProducts()
where cart.Entries.Select(c => c.ProductId).Contains(p.ProductId)
select new CartViewItem
{
Price = p.Price,
ProductId = p.ProductId,
ProductName = p.ProductName,
Quantity = cart.Entries.FirstOrDefault(c => c.ProductId == p.ProductId).Quantity
}).ToList();
型:
public class ShoppingCartEntry
{
public int ProductId { get; set; }
public int Quantity { get; set; }
}
cart.Entries
不是来自存储库。 productService.GetAllProducts()
返回实体框架的 IQueryable。
编辑:我的新代码是:
model= (from p in productService.GetAllProducts()
from c in cart.Entries
where c.ProductId == p.ProductId
select new CartViewItem
{
Price = p.Price,
ProductId = p.ProductId,
ProductName = p.ProductName,
Quantity = c.Quantity
}).ToList();
这将引发错误: Unable to create a constant value of type 'SampleApp.WebUI.Models.ShoppingCartEntry'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
我认为这应该有效...
var model = (from c in cart.Entires // The small local cart collection
let cpid = cart.Entires.Select(c2 => c2.ProjectId) //
from p in productService.GetAllProducts() // Query all Products used in cart
.Where(queryp => cpid.Contains(queryp.ProjectId)).ToList()
where p.ProductId == c.ProductId
select new CartViewItem {
p.Price,
p.ProductId,
p.Brand,
p.ProductName,
Discount = p.DiscountPercent * c.Quantity}).ToList();