Use Ienumerable or Icollection?

Asked

Viewed 789 times

5

I want to create a 1 x N mapping using the Fluent API of Entity Framework, something like: a shopping cart has several products.

In my class stroller, I have a navigation Property, which is a collection of products:

public class Produto
{
    //Atributos do produto
}

public class Carrinho
{
    //Outros atributos da classe
    public virtual IEnumerable<Produto> Produtos { get; set; } 
}

That same navigation Property could be modeled as a ICollection:

public class Carrinho
{
    //Outros atributos da classe
    public virtual ICollection<Produto> Produtos { get; set; } 
}

My question is: what is the difference between the two approaches?

1 answer

9


Using IEnumerable you can only list the collection, that is, you can read the items and nothing but change the value of the item, but not the collection.

Using ICollection can modify the collection by adding and removing items.

The documentation shows which methods you can use in each one. Of course using ICollection will be able to access everything available on IEnumerable since the first descended from the last.

If you don’t want to modify anything don’t use ICollection is a protective way not to screw up.

This can be seen in more detail at Difference between Icollection, Ilist and List?.

  • imagining that it implements Ienumerabe...it can remove some product (complete) or add?

  • @ihavenokia do not know if I understand what you mean, but if it is what I thought it could not, there is a method in IEnumerable that allows this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.