Loading Related Objects

by Sachin Singh

Posted on Saturday, 06 February 2021

Tags: Loading Related Objects Entity Framework

A database with tables without having any relationship between them is nearest to impossible to exist. We always have to deal with a database where tables have some kind of relationship among each other, the relationship may be a one-to-many, one-to-one, or many-to-many, and based on the type of relationship we need to retrieve the data and display in the application's user interface. In SQL Server we use joins to fetch related data, but Entity Framework provides us Navigation properties to navigate from one entity to another, and we rarely need Joins.

There are three different methods or ways to load related data while working with Entity Framework
    1.Lazy Loading
    2.Eager Loading
    3.Explicit Loading

Following diagram shows the relationship between four tables, collectively they represent a domain model of a blogging system.

Blog Database diagram
Blog Database Diagram

Suppose you have to display a Post with all comments on it and their respective commentator name and the name of the category the post belongs to then you will need to load three different objects (comment, Category, and User) along with the post object, This process is called as loading related objects. In Entity Framework, there are three different ways to load related objects which we will discuss in detail in coming chapters.

For now, think of Lazy loading as loading related data on-demand, which means with lazy loading, the related data are loaded into memory only when they are accessed.

Eager loading is the opposite of lazy loading where related data are loaded upfront means the entity and their related entity all are loaded into the memory at once.

In explicit loading we can decide how to load and when to load the related objects into memory, explicitly.

Each of these techniques have their own advantages and disadvantages, we will discuss them in later articles. Which technique to choose depends completely on your requirement.

It is also not necessary that you are bound to use navigation properties or it is mandatory to use many techniques, some of the time these techniques can backfire and may produce bulky SQL queries which may reduce the performance, so for complex queries we still prefer to use stored procedure with Joins and CTEs over navigation properties of Entity Framework.