Use IEnumerable or ICollection?

4

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

In my cart class, 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; } 
}

This 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?

    
asked by anonymous 14.03.2017 / 12:41

1 answer

6

Using IEnumerable can only enumerate the collection, that is, you can read the items and nothing else 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 what methods you can use on each. Obviously using ICollection can access everything that is available in IEnumerable since the first one descends from the last one.

This can be seen in more detail in Difference between ICollection, IList and List? .

    
14.03.2017 / 12:50