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?
It is because once you mark your navigation property virtual the proxy of your entity is created and it uses
HashSetfor 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.