2016-03-30 34 views
2

我有兩個類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; } 
} 

我想用這種方法,通過ownerId得到所有CartItems

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> 

回答

3

您方法的當前返回值的類型爲IEnumerable<List<CartItem>>

相反的Select你應該使用SelectMany,像這樣:

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

SelectMany變平的CartItem藏品收集到的CartItem一個集合。

+0

我認爲你的答案更好,謝謝 – temp125050

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。現在,當你加載一個購物車,你可以這樣做:

var shoppingCart = _shoppingCarts.Include("CartItems").Where(cart => cart.Id == id); 

所以,來過濾OWNERID,您可以相應地重寫查詢。只記得包括的項目。

+0

我不需要'shoppingCart實體',我想要沒有'ShoppingCart'的'CartItem'的集合 – temp125050

+0

更簡單。只要確保你的CartItems是你的Context類的一部分,所以你可以直接查詢他們 –