Entity Framework Tutorial Basics: Explicit Loading

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.