Eagerly loading related entities in Entity Framework
Recently, while working on a project, using Entity Framework I felt the need to figure out a way to eagerly load related entities in the data layer.
While I was trying to find a way to achieve this, I got to know that Entity Framework provides 3 ways to load related entities...
- Eager
- Lazy
- Explicit
Example:
Consider the entities Post and Category that are part of a blog.
The post entity could have a reference to the category associated with it.
Similarly the Category entity could have a collection of posts that it is associated with.
When we want these referenced entities to be lazy loaded we mark them as virtual.
This virtual keyword when used, loads the data of the corresponding related entity only when this navigation property is used.
For the sake of explanation, I'll just consider the code snippet for the Category class here.
As can be seen the Posts property is marked as virtual. Hence, the data in this property would be loaded only when this property is accessed in code.
If however we wish to load these related entities right at the beginning (or eagerly) when the parent entity is being loaded we can achieve the same using the Include extension method.
To use this method we would need to import the System.Data.Entity namespace.
There is an excellent article on msdn that explains all the above mentioned ways of loading related entities in Entity Framework.
I haven't used the Explicit loading method so far, but the msdn link I mentioned above explains this very well.
Hope this helps you too.
Leave a Comment