简体   繁体   English

自己实现ICollection <T> 在实体框架中可能吗?

[英]Own implementation of ICollection<T> in Entity Framework possible?

Normally POCO Classes in EF look more or less like this: 通常,EF中的POCO类看起来大致如下:

public partial class ThingEntity 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Thing> things{ get; set; }
}

They always use ICollection. 他们总是使用ICollection。

If I wanted to have more methods on the ICollection, would it be bad to write my own implementation of ICollection? 如果我想在ICollection上使用更多方法,编写我自己的ICollection实现会不好吗? I read somewhere that you shouldn't use List<T> instead of ICollection<T> , but what if I have my own implementation of ICollection? 我在某处读到您不应该使用List<T>而不是ICollection<T> ,但是如果我有自己的ICollection实现怎么办?

You can use the collection that you want. 您可以使用所需的集合。 In fact, in all my models I use List<T> , and this is really an usual pattern. 实际上,在我所有的模型中,我都使用List<T> ,这实际上是一种常见的模式。 In fact that's an interface, and, in the end, you need a concrete implementation of that interface. 实际上,这是一个接口,最后,您需要该接口的具体实现。

I tried to write an implemented class, but aften an hour I realized that I could just write Extension Methods for ICollection<T> . 我试图编写一个实现的类,但是一个小时后,我意识到我可以为ICollection<T>编写扩展方法。 That's much easier and I won't have to replace the ICollections everywhere to get the methods I need. 这要容易得多,而且我不必到处替换ICollection即可获得所需的方法。

And this helped me to write extension methods for generic lists: How to create extension method on generic collection 这帮助我为通用列表编写扩展方法: 如何在通用集合上创建扩展方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM