Monday, March 30, 2020

Lazy loading in Entity Framework Core

In Lazy Loading the data from the Main table gets loaded first in the initial load, but the data from the related tables are not loaded, they get loaded only when we access the Navigational property from the main table. To perform Lazy loading we need to enable Lazy Loading while initializing the DBContext.

Lazy Loading was introduced in EF Core 2.1. To enable lazy loading we need to install the Microsoft.EntityFrameworkCore.Proxies package and enable it with a call to UseLazyLoadingProxies.

Let us start by installing the Microsoft.EntityFrameworkCore.Proxies package.




Next let us use the UseLazyLoadingProxies method to enable the creation of proxies in the OnConfiguring method of the DbContext as follows.

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder
                    .UseLazyLoadingProxies()
                    .UseSqlServer("Server=<SQL Server>\\SQLEXPRESS;Database=UserRegistration;Trusted_Connection=True;");
            }
        }

Once we do this we are ready to use Lazy loading in the application, let us test this with a couple of queries. First let us load an Employee then we will get the department of the employee using Lazy loading as follows.

        public ActionResult<Employee> GetDetails()
        {
            var _context = new UserRegistrationContext();

            var employee = _context.Employee
                            .Where(e => e.EmployeeId == 1)
                            .FirstOrDefault<Employee>();

            var departments = employee.Department;

            return employee;
        }

We can check the underlying query executed on each line using a SQL Server profiler, when the employee query is executed the following query was triggered in SQL Server.

SELECT TOP(1) [e].[EmployeeId], [e].[Age], [e].[City], [e].[CountryId], [e].[DepartmentId], [e].[Email], [e].[Name], [e].[Phone], [e].[State]
FROM [Employee] AS [e]
WHERE [e].[EmployeeId] = 1

When the department query is executed the following query was triggered in SQL Server.

exec sp_executesql N'SELECT [e].[DepartmentId], [e].[Name]
FROM [Department] AS [e]
WHERE [e].[DepartmentId] = @__get_Item_0',N'@__get_Item_0 int',@__get_Item_0=1


Search Flipkart Products:
Flipkart.com

No comments: