Why does Entity Framework return null List<> instead of empty ones?

ぃ、小莉子 提交于 2019-11-30 00:13:41

问题


I'm pretty new in the ASP .NET MVC world. Maybe, that's the reason I can't explain to myself the cause of what is, for me, an annoying problem.

I have one class with One-To-Many relashionship.

class MyClass{
    public List<OtherClass> otherClasses {get;set;}
}

When I'm persisting one instance of this class, I fill it's relationship with an empty List<>

MyClass myClass = new MyClass(){ otherClasses = new List<OtherClass>() }
context.myClass.Add(myClass);

The problem is that, when I try to retrieve that instance, and for any reason, I try to access that list, system gives me a Null Reference Exception...

My question is: why doesn't EF return empty lists instead of null ones? Especially in this case, that I'm persisting it with an empty list?

There's any way to avoid verifing if instances are null?


回答1:


You should have your entity create those lists in the constructor. EF doesn't create dependent collections, and expects the entity to do so.

So, your case, you would make your entity like this:

class MyClass{ 
    public List<OtherClass> _otherClasses {get;set;} 

    public MyClass() {
        _otherClasses = new List<OtherClass>();
    }
} 



回答2:


Make the otherClasses collection virtual. This will enable EF to lazy load the collection.

class MyClass{
    public virtual List<OtherClass> otherClasses {get;set;}
}

Otherwise use eager loading with Include method.

context.myClass.Include(m => m.otherClasses).SingleOrDefault(m => m.Id == foo);



回答3:


So, if I understand correctly, you are adding an empty List<OtherClass> to the context and then trying to retrieve it.

I guess you have to think about how the context will track and query entities that are in its context. This is usually done by the Key of the entity. In your example, you have not given the entity a Key, therefore, the context has no handle on the entity.

Therefore, when you query, the context doesn't find an object and returns null.

If you want to initialize a new entity, I would recommend to give it at least a Key (usually the Id property), and then select by that key when you lookup later.

Hope this helps.



来源:https://stackoverflow.com/questions/9246729/why-does-entity-framework-return-null-list-instead-of-empty-ones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!