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

igor.araujo picture igor.araujo · Feb 12, 2012 · Viewed 20.6k times · Source

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?

Answer

Erik Funkenbusch picture Erik Funkenbusch · Feb 12, 2012

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>();
    }
}