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

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

使用ICollection而不是IEnumerable或List<T>的主要目的是什么?


当前回答

使用ICollection的基本思想是提供一个接口来快速访问有限数量的数据。事实上,你有一个收藏。数属性。IEnumerable更适合于某些数据链,在这些数据链中,你可以读到某个逻辑点,某个消费者特别指定的条件,或者读到枚举的结尾。

其他回答

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。

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

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

使用ICollection的基本思想是提供一个接口来快速访问有限数量的数据。事实上,你有一个收藏。数属性。IEnumerable更适合于某些数据链,在这些数据链中,你可以读到某个逻辑点,某个消费者特别指定的条件,或者读到枚举的结尾。

使用ICollection<T>是因为IEnumerable<T>接口不提供添加项、删除项或以其他方式修改集合的方法。

What I have done in the past is declare my inner class collections using IList<Class>, ICollection<Class>or IEnumerable<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 temp List<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.

导航属性通常被定义为虚拟的,这样它们就可以利用某些实体框架的功能,比如延迟加载。

如果一个导航属性可以保存多个实体(如在多对多或一对多关系中),那么它的类型必须是一个列表,其中可以添加、删除和更新条目,例如ICollection。

https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application