ICollection<T>与列表<T>在实体框架中 [英] ICollection<T> Vs List<T> in Entity Framework
问题描述
在我开始设计一些实体框架应用程序之前,我只观看了一些网络广播.我真的没有阅读那么多文档,我觉得我现在正在为此受苦.
I only watched a few webcasts before I went head first in to designing a few Entity Framework applications. I really didn't read that much documentation and I feel like I am suffering for it now.
我一直在课堂上使用 List
,效果很好.
I have been using List<T>
in my classes, and it has worked great.
现在我阅读了一些文档,它指出我应该使用 ICollection
.我改成了这个,它甚至没有引起模型上下文的变化.这是因为 List
和 ICollection
都继承了 IEnumerable
,而这才是 EF 实际需要的吗?
Now I have read some documentation and it states that I should have been using ICollection<T>
. I changed to this, and it didn't even cause a model context change. Is this because both List<T>
and ICollection<T>
inherit IEnumerable<T>
, and that is what is actually required for EF?
但是,如果是这种情况,为什么 EF 文档没有说明它需要 IEnumerable
而不是 ICollection
?
However, if this is the case, why doesn't the EF documentation state that it requires IEnumerable<T>
instead of ICollection<T>
?
无论如何,我所做的是否有任何缺点,或者我应该改变它吗?
In any case, are there any downsides to what I have done, or should I change it?
推荐答案
Entity Framework 将使用 ICollection
因为它需要支持 Add
操作,这些操作不是IEnumerable
接口的一部分.
Entity Framework would use ICollection<T>
because it needs to support Add
operations, which are not part of the IEnumerable<T>
interface.
另请注意,您正在使用ICollection
,您只是将其作为List
实现公开.List
带来了 IList
、ICollection
和 IEnumerable
>.
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>
.
至于您的更改,尽管 List
可以工作,但通过接口公开是一个不错的选择.接口定义了契约而不是实现.实施可能改变.例如,在某些情况下,实现可能是 HashSet
.(顺便说一下,这是一种不仅可以用于实体框架的思维方式.面向对象的良好做法是针对接口而不是实现进行编程.实现可以并且将会改变.)
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.)
这篇关于ICollection<T>与列表<T>在实体框架中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!