4

I have two classes ShoppingCart and CartItems like this:

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; }
}

I want get all CartItems by ownerId using this method:

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

but it returns an error :

Cannot implicitly convert type System.Collections.Generic.List<System.Collections.Generic.ICollection<CartItem>>'to System.Collections.Generic.IEnumerable<CartItem>

2 Answers 2

5

The current return value of your method is of type IEnumerable<List<CartItem>>.

Instead of Select you should use SelectMany, like this:

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

SelectMany flattens the collection of collections of CartItem to one collection of CartItem.

Sign up to request clarification or add additional context in comments.

Comments

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; }
}

You forgot to add virtual to your ICollection of CartItems. Now when you load a shoppingCart, you can do:

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

So, to filter for ownerId, you can rewrite your query correspondingly. Just remember to include the items.

2 Comments

I dont need shoppingCart Entity , I want get collection Of CartItem without ShoppingCart
Even easier. Just make sure your CartItems are part of your Context class, so you can query on them directly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.