为什么使用 ICollection 而不是 IEnumerable 或 List<T>多对多/一对多关系? [英] Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

查看:25
本文介绍了为什么使用 ICollection 而不是 IEnumerable 或 List<T>多对多/一对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在教程中经常看到这种情况,导航属性为 ICollection.

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

这是实体框架的强制性要求吗?我可以使用 IEnumerable 吗?

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

使用 ICollection 而不是 IEnumerable 甚至 List 的主要目的是什么?

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

推荐答案

通常您的选择取决于您需要访问哪些方法.一般来说 - IEnumerable<>(MSDN:http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) 获取只需要迭代的对象列表,ICollection<>(MSDN:http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) 用于需要迭代和修改的对象列表,List<> 用于需要迭代和修改的对象列表、排序等(请参阅此处获取完整列表:http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

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).

从更具体的角度来看,延迟加载与选择类型有关.默认情况下,实体框架中的导航属性带有更改跟踪并且是代理.为了将动态代理创建为导航属性,虚拟类型必须实现ICollection.

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.

表示关系多"端的导航属性必须返回实现 ICollection 的类型,其中 T 是关系另一端的对象类型.-创建 POCO 代理的要求MSDN

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

有关定义和管理关系的更多信息MSDN

这篇关于为什么使用 ICollection 而不是 IEnumerable 或 List&lt;T&gt;多对多/一对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆