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>
?
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>
?
There are some basics difference between ICollection and IEnumerable
Simple Program:
What I have done in the past is declare my inner class collections using
IList<Class>
,ICollection<Class>
orIEnumerable<Class>
(if static list) depending on whether or not I will have to do any number of the following in a method in my repository: enumerate, sort/order or modify. When I just need to enumerate (and maybe sort) over objects then I create a tempList<Class>
to work with the collection within an IEnumerable method. I think this practice would only be effective if the collection is relatively small, but it may be good practice in general, idk. Please correct me if there is evidence as to why this would not good practice.Usually what you choose will depend on which methods you need access to. In general
IEnumerable<>:
According to MSDN documentation
ICollection<>:
According to MSDN documentation
List<>:
According to MSDN documentation
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
.More information on Defining and Managing RelationshipsMSDN
Responding to your question about
List<T>
:List<T>
is a class; specifying an interface allows more flexibility of implementation. A better question is "why notIList<T>
?"To answer that question, consider what
IList<T>
adds toICollection<T>
: integer indexing, which means the items have some arbitrary order, and can be retrieved by reference to that order. This is probably not meaningful in most cases, since items probably need to be ordered differently in different contexts.The basic idea of using
ICollection
is a provide an interface to readonly-access to some finite amount of data. In fact you have a ICollection.Count property.IEnumerable
is more suitable for some chain of the data where you read till some logical point, some condition esplicitly specified by consumer or till the end of the enumeration.ICollection<T>
is used because theIEnumerable<T>
interface provides no way of adding items, removing items, or otherwise modifying the collection.