tem*_*050 4 c# generics entity-framework
我有两节课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; }
}
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)
您的方法的当前返回值的类型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
。