我有两个类ShoppingCart
和CartItems
,如下所示:
public class ShoppingCart
{
public Guid Id { get; set; }
public DateTime CreatedOn { get; set; }
public Guid OwnerId { get; set; }
public ICollection<CartItem> Items { get; set; }
}
public class CartItem
{
public Guid Id { get; set; }}
public int Quantity { get; set; }
public Guid ProductId { get; set; }
public Guid ShoppingCartId { get; set; }
}
我希望CartItems
使用此方法获取所有ownerId
:
public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
return _shoppingCarts.Where(row => row.OwnerId == ownerId)
.Select(row => row.Items)
.ToList() ;
}
但它返回错误:
Cannot implicitly convert type System.Collections.Generic.List<System.Collections.Generic.ICollection<CartItem>>'to System.Collections.Generic.IEnumerable<CartItem>
答案 0 :(得分:4)
您方法的当前返回值是Select
类型。
而不是public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
return _shoppingCarts.Where(row => row.OwnerId == ownerId).SelectMany(row => row.Items).ToList() ;
}
,您应该使用SelectMany
,如下所示:
SelectMany
CartItem
将CartItem
的集合集合展平为NavigationDrawer
的一个集合。
答案 1 :(得分:0)
public class ShoppingCart
{
public Guid Id { get; set; }
public DateTime CreatedOn { get; set; }
public Guid OwnerId { get; set; }
public virtual ICollection<CartItem> Items { get; set; }
}
您忘记将虚拟添加到您的ICollection of CartItems。现在,当您加载shoppingCart时,您可以执行以下操作:
var shoppingCart = _shoppingCarts.Include("CartItems").Where(cart => cart.Id == id);
因此,要过滤ownerId,您可以相应地重写查询。请记住包含这些项目。