C# 如何在实体框架中返回嵌套列表
我有两个类C# 如何在实体框架中返回嵌套列表,c#,entity-framework,generics,C#,Entity Framework,Generics,我有两个类ShoppingCart和cartimes,如下所示: 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 clas
ShoppingCart
和cartimes
,如下所示:
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; }
}
public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
return _shoppingCarts.Where(row => row.OwnerId == ownerId).SelectMany(row => row.Items).ToList() ;
}
但它返回一个错误:
Cannot implicitly convert type System.Collections.Generic.List<System.Collections.Generic.ICollection<CartItem>>'to System.Collections.Generic.IEnumerable<CartItem>
无法将类型System.Collections.Generic.List隐式转换为System.Collections.Generic.IEnumerable
因此,要筛选ownerId,可以相应地重写查询。只需记住包括项目即可 方法的当前返回值的类型为
IEnumerable
选择您应该使用的,而不是,如下所示:
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; }
}
public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
return _shoppingCarts.Where(row => row.OwnerId == ownerId).SelectMany(row => row.Items).ToList() ;
}
public IEnumerable GetCartItems(Guid所有者ID)
{
return _shoppingCarts.Where(row=>row.OwnerId==OwnerId)。选择many(row=>row.Items)。ToList();
}
SelectMany
将CartItem
集合的集合展平为一个CartItem
我不需要shoppingCart实体
,我希望在不使用shoppingCart
的情况下获得CartItem
集合更容易。只要确保CartItems是上下文类的一部分,就可以直接查询它们
public IEnumerable<CartItem> GetCartItems(Guid ownerId)
{
return _shoppingCarts.Where(row => row.OwnerId == ownerId).SelectMany(row => row.Items).ToList() ;
}