This video is available to students only

Adding Eager Loading

In this lesson, we're going to add code for eager loading

Eager loading#

We saw that our requests are not returning data from another table, category request doesn't show courses, and courses request does not show category, learnings and requirements. This is what we want to fix now. This is called loading of navigation properties.

For this, we can either use lazy loading which means Entity Framework will add all the navigation properties to our response every time, which is not ideal because you don't have a choice of what to return and what not to.

However, we have a better option of using eager loading, where we are explicitly telling Entity framework which navigation property to load alongside the returning entity. This is a context feature, so we'll have to go to the implementation of the interfaces which is inside the Infrastructure project. Let's go to the CategoryRepository first. Inside the GetControllersAsync method, before ToListAsync method, we can append our Include request because ToListAsync is the call to the database and we need to do it before. Using Include statement will ask the database for the navigation property that we want in our response. We want to include courses in the getCategories, so we can use lambda expression and use c which goes to c.Courses and that's it.

We need to do the same thing for the GetCategoryByIdAsync method; Include(c => c.Courses). We will receive an error because FindAsync method doesn't accept IQueryable. This is IQueryable because we're building a query before using ToListAsync or FindAsync. If we don't have the include statement, it's not IQueryable, but now it is, so we will have to replace it with FirstorDefaultAsync which takes an expression as a parameter, so we can write x => x.Id == id.

Start a new discussion. All notification go to the author.