One of the features that Entity Framework offers is Explicit Loading. This allows you to lazily load related entities, even with lazy loading disabled. The only difference is that you need a explicit call to do it(by using the Load method on the related entity’s entry):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var context = new SchoolEntities()) | |
{ | |
course = context.Course.Find(4041); | |
// Load the students for a given course | |
context.Entry(course) | |
.Collection(c => c.Students) | |
.Load(); | |
} |
Let’s try to change our code to do this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var context = new SchoolEntities()) | |
{ | |
context.Configuration.LazyLoadingEnabled = true; //Is the default setting | |
course = context.Course.Find(4041); | |
// Load the female students for a given course | |
context.Entry(course) | |
.Collection(c => c.Students) | |
.Query() | |
.Where(p=> p.Gender=="Female") //Will still return all students | |
.Load(); | |
} |
However if we look at the results we get back, it still contains all students. To enable filtering when using explicit loading, you’ll have to make sure that LazyLoading is disabled. If we change the code to incorporate this, it will work as expected:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var context = new SchoolEntities()) | |
{ | |
context.Configuration.LazyLoadingEnabled = false; | |
course = context.Course.Find(4041); | |
// Load the female students for a given course | |
context.Entry(course) | |
.Collection(c => c.Students) | |
.Query() | |
.Where(p=> p.Gender=="Female") //Will return only female students | |
.Load(); | |
} |