如何在实体框架中返回嵌套的List

时间:2016-03-30 08:41:49

标签: c# entity-framework generics

我有两个类ShoppingCartCartItems,如下所示:

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>

2 个答案:

答案 0 :(得分:4)

您方法的当前返回值是Select类型。

而不是public IEnumerable<CartItem> GetCartItems(Guid ownerId) { return _shoppingCarts.Where(row => row.OwnerId == ownerId).SelectMany(row => row.Items).ToList() ; } ,您应该使用SelectMany,如下所示:

SelectMany

CartItemCartItem的集合集合展平为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,您可以相应地重写查询。请记住包含这些项目。