zoukankan      html  css  js  c++  java
  • Entity Framework Tutorial Basics(38):Explicit Loading

    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:

    Entity Framework tutorial 4.3 dbcontext

    The load method to get the Standard entity is shown below:

    Entity Framework tutorial 4.3 dbcontext

    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.

  • 相关阅读:
    UVA 11991 Easy Problem from Rujia Liu(map,vector的使用)
    UVA 11995 I Can Guess the Data Structure! (STL应用)
    HDU 2795 Billboard(线段树,单点更新)
    HDU 1394 Minimum Inversion Number (线段树,单点更新)
    UVA 11827 Maximum GCD(读入技巧,stringstream的使用)
    contest 2 总结
    Const 1 总结
    开始进行大量题目练习
    函数式线段树的个人理解
    poj 2318 TOYS
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5649436.html
Copyright © 2011-2022 走看看