ICollection的< T> VS名单< T>在实体框架 [英] ICollection<T> Vs List<T> in Entity Framework

查看:192
本文介绍了ICollection的< T> VS名单< T>在实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只看过一些网络广播之前,我中设计一些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.

我一直使用列表< T> 在我的课,和它一直很大。

I have been using List<T> in my classes, and it has worked great.

现在我看了一些文档和它说我应该一直在使用的ICollection&LT; T&GT; 。我改变了这一点,它甚至没有引起模型方面的变化。这是因为这两个列表&LT; T&GT; 的ICollection&LT; T&GT; 继承的IEnumerable&LT; T&GT; ,那就是什么是真正需要的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&LT;的而不是的ICollection&LT; T&GT T&GT ;

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?

推荐答案

实体框架将使用的ICollection&LT; T&GT; ,因为它需要支持添加的操作,这是不是一部分的的IEnumerable&LT; T&GT; 接口

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

另外请注意,您的的使用的ICollection&LT; T&GT; ,你只是暴露其作为列表&LT; T&GT ; 的实施。 列表&LT; T&GT; T&GT; 的ICollection&LT; T&GT; <的IList&LT带来沿/ code>和的IEnumerable&LT; T&GT;

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

至于你的变化,通过接口暴露是个不错的选择,尽管列表&LT; T&GT; 工作。该接口定义了合同,但是没有实现。实施的可能的变化。在某些情况下,也许实现可能是一个的HashSet&LT; T&GT; ,例如。 (这是您可以使用的不仅仅是实体框架的更多,顺便一种思维定势,一个良好的面向对象的做法是对的接口,而不是实现编程。实现可以和将发生改变。)

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的&LT; T&GT; VS名单&LT; T&GT;在实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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