Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 211
igor.araujo Avatar asked Feb 12 '12 05:02

igor.araujo


People also ask

Is it better to return empty list or null?

Generally it's best to return empty collections, but sometimes (rarely): null might mean something more specific; your API (contract) might force you to return null .

Can ToList return null?

If you have a Query that returns a empty set then ToList returns null. You would probably expect it to return an empty list (Count = 0), which is the case when using data providers for SQL Server.

Does Linq ever return null?

in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Does this answer the question?

How do you return a null object in C#?

So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided.


2 Answers

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>();     } }  
like image 159
Erik Funkenbusch Avatar answered Oct 05 '22 02:10

Erik Funkenbusch


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); 
like image 23
Eranga Avatar answered Oct 05 '22 03:10

Eranga