Saturday, December 31, 2022

.Net Core Eager Loading related data.

As I continue playing around with .Net 6, I stumbled upon to its new feature which is to auto-include related data.

In most cases in app development, data are related and it requires to be included when you try to get the main entity. For instance you have a User table that has a related data to roles, you may want to include the user roles when you fetch the user/s. 

What I previously do is 

var results = await dbSet.Include(c => c.UserRoles).ToListAsync();

With the updates from Microsoft, Now I can add the code below in my DB Context

modelBuilder.Entity<User>().Navigation(e => e.UserRoles).AutoInclude();

That's my year-end post to remind my future self about this feature.

For reference please refer to link below.

https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#model-configuration-for-auto-including-navigations