Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

I see this a lot in tutorials, with navigation properties as ICollection<T>.

Is this a mandatory requirement for Entity Framework? Can I use IEnumerable?

What's the main purpose of using ICollection instead of IEnumerable or even List<T>?

like image 787
Jan Carlo Viray Avatar asked Apr 11 '12 20:04

Jan Carlo Viray


People also ask

Should I use ICollection or IEnumerable?

IEnumerable contains only GetEnumerator() method, like read-only iterate. ICollection is one step ahead of IEnumerable. 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.

What is the difference between ICollection and list?

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

Does ICollection implement IEnumerable?

ICollection<T> interface. The ICollection interface extends IEnumerable; IDictionary and IList are more specialized interfaces that extend ICollection. An IDictionary implementation is a collection of key/value pairs, like the Hashtable class.

Is IEnumerable faster than list C#?

IEnumerable is more efficient and faster when you only need to enumerate the data once. The List is more efficient when you need to enumerate the data multiple times because it already has all of it in memory.


2 Answers

Usually what you choose will depend on which methods you need access to. In general - IEnumerable<> (MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) for a list of objects that only needs to be iterated through, ICollection<> (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) for a list of objects that needs to be iterated through and modified, List<> for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

From a more specific standpoint, lazy loading comes in to play with choosing the type. By default, navigation properties in Entity Framework come with change tracking and are proxies. In order for the dynamic proxy to be created as a navigation property, the virtual type must implement 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 information on Defining and Managing RelationshipsMSDN

like image 76
Travis J Avatar answered Nov 01 '22 11:11

Travis J


ICollection<T> is used because the IEnumerable<T> interface provides no way of adding items, removing items, or otherwise modifying the collection.

like image 21
Justin Niessner Avatar answered Nov 01 '22 12:11

Justin Niessner