EF4.1 POCO: Why should I use ICollection

In almost all examples, POCO classes created for Entity Framework 4.1 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 a problem in my code where I need to access a collection member by index, for example:

Person Paul = TravelTicket.Members [3];

Cannot apply indexing with [] to an expression like "System.Collections.Generic.ICollection

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

+6
source share
3 answers

This is because after you have marked your navigation property virtual, your organization’s proxy server has been created and uses a HashSet for navigation properties. The hash set does not allow indexing. Accessing related objects by index does not seem to be a good approach, because retrieving an object from the database does not guarantee that related objects will always have the same index in the collection.

+11
source

Just use ToList ():

 Person Paul = TravelTicket.Members.ToList()[3]; 

EF is not going to request data until you actually try to access it - and the collection does not try until you collapse it, and ToList must create an instance of each instance.

Better yet, check out:

 Person Paul = TravelTicket.Members.Where(m=>m.Id == 3); // or some such similar filter 

Then you are only the ONE Member instance - the one you want.

Note that you may need .AsQueryable () members. Instead, I never remember ...

0
source

ICollection implements IEnumerable , you can get the element by index using the Enumerable.ElementAt<TSource> method

0
source

Source: https://habr.com/ru/post/891107/


All Articles