Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF4.1 POCO: Why should I use ICollection

In nearly all examples of POCO classes created for Entity Framework 4.1 collections are defined using the ICollection interface:

public class TravelTicket
{
    public virtual int Id { get; set; }
    public string Destination { get; set; }
    public virtual ICollection<Person> Members { get; set; }
}

However, this causes an issue in my code where I need to access a member of the collection by index, e.g.:

Person Paul = TravelTicket.Members[3];

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.ICollection

So how do I get round this problem and should I always use ICollection for my POCO collections?

like image 573
FloatLeft Avatar asked Jun 22 '11 11:06

FloatLeft


People also ask

Why is ICollection used?

If we want some more functionality like Add or remove element, then it is better to go with ICollection because we cannot achieve that with IEnumerable. ICollection extends IEnumerable. It supports non-index based operations like - Add item in Collection, remove, check contained item etc.

What is the difference between ICollection and list?

ICollection<T> is an interface, List<T> is a class.

What is the use of virtual keyword in Entity Framework?

You should use virtual keyword, when you want to load data with lazy loading. lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time it is accessed. Lazy loading of the Posts collection can be turned off by making the Posts property non-virtual.

How do I create an instance of ICollection?

ICollection is an interface, you can't instantiate it directly. You'll need to instantiate a class that implements ICollection ; for example, List<T> . Also, the ICollection interface doesn't have an Add method -- you'll need something that implements IList or IList<T> for that.


1 Answers

It is because once you mark your navigation property virtual the proxy of your entity is created and it uses HashSet for navigation properties - hash set doesn't allow indexing. Accessing related entities by index doesn't seem like good approach because retrieving entity from database doesn't ensure that related entities will always have the same index in the collection.

like image 161
Ladislav Mrnka Avatar answered Oct 16 '22 07:10

Ladislav Mrnka