Entity Framework Default Collection Value

If you have a class that has collections, the default value of these collections are NULL when you Entity is loaded by Entity Framework. If you are using Lazy Loading, than these properties are virtual. It is not recommended to initialize the collection in the constructor if these are virtual. Not because it is Entity Framework but because initializing a property that is virtual is never a good practice in .Net. The reason is beyond the scope of this article but just keep in mind that even if it is initialized by the constructor, the class that inherit your class may still use the property before it is initialized which could cause an exception.

Still, if you are using Entity Framework without Lazy Loading, your properties should not be virtual and by default, these collections must be initialized otherwise, a NULL value is returned.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.