Why does Entity Framework return null list instead?

Why does Entity Framework return null list instead?

This will enable EF to lazy load the collection. Otherwise use eager loading with Include method. So, if I understand correctly, you are adding an empty List 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.

When do database queries return an empty set?

Database queries return result sets. An empty set is a reasonable answer; it means you don’t have any of the things searched for. I would argue that your code is going to far in canonicalization of the result.

How to create dependent collections in Entity Framework?

You should have your entity create those lists in the constructor. EF doesn’t create dependent collections, and expects the entity to do so. Make the otherClasses collection virtual. This will enable EF to lazy load the collection. Otherwise use eager loading with Include method.

How to initialize an entity in C #?

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. Thanks for contributing an answer to Stack Overflow!

How to test for null or empty object?

Give me the first item matching this criteria.. there are none, here is a null. Your code will throw an exception if it tries to use it. An alternative if you don’t like testing for nulls, or empty objects, though is to always return a list of objects. That way you can do a for each on the list and it naturally does nothing if nothing is found.

How to handle null object property with firstordefault?

But which will give you null if there are no records satisfying the condition (because in the absence of first value it will give you the default value, for reference type objects the default value is null ), you you should check for null before accessing the value, which will throws NullReferenceException. So Use like this:

Is it possible to return a null reference?

This link says it is not possible to return a non-null reference type: https://msdn.microsoft.com/en-us/library/bb360179 (v=vs.110).aspx Database queries return result sets. An empty set is a reasonable answer; it means you don’t have any of the things searched for. I would argue that your code is going to far in canonicalization of the result.