Load Relational Data Using Include and ThenInclude in Entity Framework Core

Entity Framework Core allows you to load related entities using the navigation properties in your model. Related entities can be loaded using different ways. If you use Eager loading, it will enable you to access relational data in a single database call. In Eager loading, related data can be loaded using Include and ThenInclude methods.

Include

Consider the following model with three simple entities.
    public class User
    {
        public Int64 UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Password { get; set; }
        public ICollection<UserRole> UserRoles { get; set; }

    }
    public class UserRole
    {
        public Int64 UserRoleID { get; set; }
        public Int64 UserID { get; set; }
        public Int64 RoleID { get; set; }
        public User User { get; set; }
        public Role Role { get; set; }
    }

    public class Role
    {

        public Int64 RoleID { get; set; }
        public string RoleName { get; set; }
        public string Description { get; set; }
        public ICollection<UserRole> UserRoles { get; set; }

    }

To retrieve all users with their roles, you can use the following query.

using (var context = new UserContext())
{
    var User = context.Users
        .Include(ur=> ur.UserRoles)
         .ToList();
}

ThenInclude

You can drill down through relationships to include multiple levels of related data using the ThenInclude method. The following example retrieves data from Users, UserRoles, and Roles tables.

using (var context = new UserContext())
{
    var User = context.Users
        .Include(ur=> ur.UserRoles)
         .ThenInclude(r => r.Roles)
         .ToList();
}

 


Search