如何在实体框架中返回嵌套列表

tem*_*050 4 c# generics entity-framework

我有两节课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; }
}
Run Code Online (Sandbox Code Playgroud)

我想CartItems通过ownerId使用这种方法获得所有:

public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
    return _shoppingCarts.Where(row => row.OwnerId == ownerId)
                         .Select(row => row.Items)
                         .ToList() ; 
}
Run Code Online (Sandbox Code Playgroud)

但它返回一个错误:

Cannot implicitly convert type System.Collections.Generic.List<System.Collections.Generic.ICollection<CartItem>>'to System.Collections.Generic.IEnumerable<CartItem>
Run Code Online (Sandbox Code Playgroud)

Dom*_*see 5

您的方法的当前返回值的类型IEnumerable<List<CartItem>>

而不是Select你应该使用SelectMany,像这样:

public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
    return _shoppingCarts.Where(row => row.OwnerId == ownerId).SelectMany(row => row.Items).ToList() ; 
}
Run Code Online (Sandbox Code Playgroud)

SelectMany将 的集合的集合扁平化为 的CartItem一个集合CartItem