Entity Framework Tutorial Basics(38):Explicit Loading

來源:互聯網
上載者:User

標籤:

Explicit Loading with DBContext

Even with lazy loading disabled, it is still possible to lazily load related entities, but it must be done with an explicit 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 (var context = new SchoolDBEntities()){    //Disable Lazy loading    context.Configuration.LazyLoadingEnabled = false;                    var student = (from s in context.Students                        where s.StudentName == "Bill"                        select s).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 will execute two 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(38):Explicit Loading

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.