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.
Any virtual ICollections will be lazy loaded unless marked otherwise. Using of virtual keyword only related to lazy loading.
DbSet.Create() method
http://stackoverflow.com/questions/7311949/ramifications-of-dbset-create-versus-new-entity
http://stackoverflow.com/questions/6312981/lazy-loading-properties-after-an-insert
DbSet.Create() method
http://stackoverflow.com/questions/7311949/ramifications-of-dbset-create-versus-new-entity
http://stackoverflow.com/questions/6312981/lazy-loading-properties-after-an-insert
Explicit loading
Even with lazy loading off, you can load related entities lazily. By explicitly calling Load method.
0 comments:
Post a Comment