EF Code First 4.1 Lazy Loading

EF Code First 4.1 Lazy Loading

  • Comments 0

EF Code First supports Lazy Loading as Model (edmx). You need to define the navigation properties to set the relationship to load the query.

So if we try to implement the below code

   1:  public class Department
   2:  {
   3:      [Key] //To make it Primary Key and Identity
   4:      public int DeptId { get; set; }
   5:      public string DeptName { get; set; }
   6:   
   7:      //Create Employee navigation property for Lazy Loading (1:many)
   8:      public virtual ICollection<Employee> Employees { get; set; }
   9:  }
  10:   
  11:  /// <summary>
  12:  /// Employee class
  13:  /// </summary>
  14:  public class Employee
  15:  {
  16:      [Key] //To make it Primary Key and Identity
  17:      public int EmpId { get; set; }
  18:      public string FirstName { get; set; }
  19:      public string LastName { get; set; }
  20:      public int DeptId { get; set; }
  21:   
  22:      //Create Department navigation property for Lazy Loading
  23:      public virtual Department Department { get; set; }
  24:  }

Hence the line 8 and 23 together with virtual would create the 1:many relationship.

image

After adding data if we try to write the below code it would Lazy Load the data

using (var db = new EmpDeptContext())
{
    var d = from dept in db.Depts
            select dept;
    foreach (var d1 in d)
    {
        Console.WriteLine("+++++++++++++");
        Console.WriteLine(d1.DeptName);
        Console.WriteLine("+++++++++++++");

        foreach (var e1 in d1.Employees)
        {
            Console.WriteLine(e1.FirstName + " " + e1.LastName);
        }
        Console.WriteLine("=============================");
    }
}

And by adding .Include we will get similar Immediate Loading.

var d = from dept in db.Depts.Include("Employees")
        select dept;

Namoskar!!!

Leave a Comment
  • Please add 4 and 5 and type the answer here:
  • Post