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.
public class Category { public Category() { this.Posts = new List<Post>(); }
public int Id { get; set; }
[Required] [MaxLength(50)] public string Name { get; set; }
[MaxLength(200)] public string Description { get; set; }
//The Posts property collection is loaded lazily public virtual ICollection<Post> Posts { get; set; } }
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.
using (var context = new BloggingContext()) { // Load all categories and related posts var categories = context.Categories .Where(c => c.Name == "C#") .Include(c => c.Posts) .ToList<Category>(); }
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.