On many-many/one-many connections, why use ICollection instead of IEnumerable or ListT>?

c# code-first entity-framework icollection


I often see navigation properties described in tutorials asICollection<T> .

Is this a condition that Entity Framework must meet? Could I utilizeIEnumerable ?

What is the primary goal of utilizingICollection in place ofIEnumerable and evenList<T> ?

4/2/2014 9:19:23 PM

Accepted Answer

What you choose will often rely on the approaches you need. generally -IEnumerable<> For a list of items that merely has to be iterated over, see (MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx).ICollection<> For a list of items that need to be updated iteratively, see (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx).List<> if a list of items has to be updated, sorted, iterated over, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

More specifically, when selecting the type, slow loading is a factor. Entity Framework's navigation properties are proxies by default and provide change tracking. The virtual type must implements the navigation property creation for the dynamic proxy.ICollection .

A navigation property that represents the "many" end of a relationship must return a type that implements ICollection, where T is the type of the object at the other end of the relationship. -Requirements for Creating POCO ProxiesMSDN

More details on Relationship Definition and ManagementMSDN

10/22/2019 9:49:48 PM

Popular Answer

ICollection<T> is employed due to theIEnumerable<T> interface does not provide a mechanism to add, remove, or change the collection in any other manner.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow