A database with tables without any relationship between them is almost impossible to exist. We always have to deal with a database where tables have some kind of relationship with 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 it in the application's user interface. In SQL Server, we use joins to fetch related data, but Entity Framework provides us with 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:
- Lazy Loading
- Eager Loading
- Explicit Loading
The following diagram shows the relationship between four tables. Collectively, they represent a domain model of a blogging system.
Suppose you have to display a post with all comments on it and their respective commentator names and the name of the category the post belongs to, you will need to load three different objects (i.e., Comment, Category, and User) along with the Post object. This process is called loading related objects. In Entity Framework, there are three different ways to load related objects, which we will discuss in detail in the upcoming chapters.
For now, think of lazy loading as loading related data on demand, which means that 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 is loaded upfront, meaning that the entity and its related entities 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 has its 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 that you use many techniques. Sometimes, these techniques can backfire and may produce bulky SQL queries, which may reduce the performance, so for complex queries, we still prefer to use the stored procedures with Joins and CTEs over navigation properties of Entity Framework.