ICollection<T> Vs List<T> in Entity Framework

笑着哭i 提交于 2019-11-26 15:46:52

Entity Framework would use ICollection<T> because it needs to support Add operations, which are not part of the IEnumerable<T> interface.

Also note that you were using ICollection<T>, you were merely exposing it as the List<T> implementation. List<T> brings along with it IList<T>, ICollection<T>, and IEnumerable<T>.

As for your change, exposing via the interface is a good choice, despite List<T> working. The interface defines the contract but not the implementation. The implementation could change. In some instances, perhaps the implementation could be a HashSet<T>, for example. (This is a mindset you could use for more than just Entity Framework, by the way. A good object-oriented practice is to program towards the interface and not the implementation. Implementations can and will change.)

They picked the interface they did because it gives a comprehensible abstraction over the magic queries the Entity Framework performs when you use Linq.

Here's the difference between the interfaces:

  • IEnumerable<T> is read-only
  • You can add and remove items to an ICollection<T>
  • You can do random access (by index) to a List<T>

Out of those, ICollection and IEnumerable map well to database operations, since querying and adding/removing entities are things you might do in a DB.

Random access by index doesn't map as well, since you'd have to have an existing query result to iterate over, or each random access would query the database again. Also, what would the index map to? Row number? There aren't a lot of row number queries you'd want to do, and it isn't useful at all in building up bigger queries. So they simply don't support it.

ICollection<T> is supported, and will allow you to both query and change data, so use that.

The reason List<T> works to begin with is because the EF implementation ends up returning one in the end. But that's at the end of your query chain, not at the beginning. So making your properties ICollection<T> will make it more obvious that the EF creates a bunch of SQL and only returns a List<T> at the end, rather than doing queries for each level of Linq that you use.

ICollection differs from IEnumerable in that you can actually add items to the collection, whereas with IEnumerable you can't. So in your POCO classes, for instance, you want to use ICollection if you intend to allow the collection to be added to. Make the ICollection virtual to benefit from lazy loading too.

Although the question has been posted years back, its still valid when someone is looking for the same scenario.

There is a recent [2015] CodeProject article which explains the difference in much detail and graphical representation with sample code. It is not focused directly at EF but still hope it will be of greater help:

List vs IEnumerable vs IQueryable vs ICollection vs IDictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!