Monday, March 30, 2020

EFCore - Loading Dependent table data

When we Generate the Model classes using Entity Framework Core it creates Navigational properties for the Model classes which have a Foreign Key relation. Using these Navigational properties we can load dependent data in different ways.

In our previous examples we have seen the Employee table has Foreign Key relation with the Department table and the Country table, when we generate the Model classes using Entity Framework Core the Employee class will have reference to the related classes, the Employee model class will be as follows.

    public partial class Employee
    {
        public int EmployeeId { get; set; }
        public int? DepartmentId { get; set; }
        public string Name { get; set; }
        public int? Age { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public int? CountryId { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }

        public virtual Country Country { get; set; }
        public virtual Department Department { get; set; }
    }

Notice the last 2 lines in the model class, they provide a Navigational property link to the Country and Department classes. Entity Framework core allows us to use these Navigational properties and load dependent table data in different ways.

Eager Loading: In Eager Loading the data from the main table and the data from the related tables are loaded at once during the initial load. This approach is suitable when the size of the datasets are small and the probability of using the related table’s data is high. Eager loading is achieved using the Include() method.

Lazy Loading: 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.

Explicit Loading: Explicit loading is a kind of lazy loading but the dependent objects are not loaded automatically, but we will have to explicitly load the dependent objects whenever needed. We have to use the Load() method to load related entities explicitly.


Search Flipkart Products:
Flipkart.com

No comments: