且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ICollection的< T> VS名单< T>在实体框架

更新时间:2022-04-27 15:21:13

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

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