Lazy loading in entity framework

using (var ctx = new EmployeeDBEntities()) 
{
//Loading Employee only
IList<Employee> empList = ctx.Employee.ToList<Employee>();
Employee emp = empList[0]; //Loads Employee address for particular Employee only (seperate SQL query)
EmployeeAddress address = emp.EmployeeAddress.FirstOrDefault();
}
SELECT 
[Extent1].[EmployeeID] AS [EmployeeID],
[Extent1].[EmployeeName] AS [EmployeeName],
[Extent1].[ContactNo] AS [ContactNo],
[Extent1].[EmailID] AS [EmailID]
FROM [dbo].[Employee] AS[Extent1]
exec sp_executesql N'SELECT 
[Extent1].[ID] AS [ID],
[Extent1].[EmpID] AS [EmpID],
[Extent1].[Address] AS [Address]
FROM [dbo].[EmployeeAddress] AS [Extent1]
WHERE [Extent1].[EmpID] =
@EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1
namespace MVC_Tutorials 
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
public partial class EmployeeDBEntities : DbContext
{
public EmployeeDBEntities()
: base("name=EmployeeDBEntities")
{
this.Configuration.LazyLoadingEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
}
  • context.Configuration.ProxyCreationEnabled should be true.
  • context.Configuration.LazyLoadingEnabled should be true.
  • Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
.Net Developer

.Net Developer

I’m a professional Technical writer and Software Development with more than 5 years of experience.