[ACCEPTED]-Why does Entity Framework return null List<> instead of empty ones?-nullreferenceexception

Accepted answer
Score: 30

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

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

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

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

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

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

Otherwise 1 use eager loading with Include method.

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

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

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

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

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

Hope this helps.

More Related questions