Tuesday, December 24, 2013

Loading Entities in Entity Framework

In Entity Framework you can load data in few different ways,
  • Eager loading
  • Lazy loading
  • Explicit loading

Eager Loading

Here query for a one type of entity also loads other related entities as a part of the query. You can load related entities by using Include method. Include is an extension method.

        List<Employee> employees = context.Employees
            .Include(e => e.Courses)
            .ToList();


        List<Employee> employees2 = context.Employees
            .Include("Courses")
            .ToList();

This will generate a left outer join (See diagram for types of joins) thereby, if no record found it will return null for them.



You can also load multiple levels of related entities. In eager loading, there won't be multiple database calls.  It retrieves all data at once. The downside is, it creates large nested queries which has a performance impact. Therefore avoid using multiple Include statements in a single LINQ query. See Performance considerations. See SO Questions.

Lazy Loading

Loads related entities automatically the first time the property referring the entity is accessed.

Lazy loading and serialization doesn't get together well. Most serializers work by accessing each property of an instance of a type. This property access triggers lazy loading. Therefore it is recommended to turn off lazy loading before serializing an entity. 


Explicit loading

Even with lazy loading off, you can load related entities lazily. By explicitly calling Load method.

References

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook