Explicit Loading with DBContext
Even with lazy loading disabled, it's still possible to lazily load related entities, but it must was done with an Explici T call. Use the Load method of Dbentityentry object to accomplish this.
The following code explicitly loads standard of particular Student using the Reference () method of Dbentityentry:
using(varContext =Newschooldbentities ()) { //Disable Lazy LoadingContext. configuration.lazyloadingenabled =false; varStudent = ( fromSinchcontext. StudentswhereS.studentname = ="Bill" Selects). Firstordefault<student>(); Context. Entry (student). Reference (S=S.standard). Load ();}
If you run the code shown above, you can see that it first loads student but not standard, as shown below:
The Load method to get the standard entity is shown below:
The code shown above would execute with the different database queries. The first query gets Student and the second query gets standard.
Load Collection:
Use the Collection () method instead of Reference () method to load Collection navigation property. The following example loads the courses of student.
using (var context = new Schooldbentities ()) {context. configuration.lazyloadingenabled = false var student = (from s in context. Students where s.studentname = = " bill " select s). Firstordefault<student> (); Context. Entry (student). Collection (s => s.courses). Load ();}
Note: The Load extension method works just like ToList, except that it avoids the creation of the list altogether.
Entity Framework Tutorial Basics: Explicit Loading