Search code examples
c#linq.net-coreentity-framework-coreasp.net-core-identity

Entity Framework Core : Include not working for many-to-many relationship


I'm having trouble with .Include() not working for many-to-many relationships in Entity Framework Core. My setup works fine for one-to-many relationships, but the related entities are not being loaded for many-to-many relationships.

Entities:

public class AppUser : IdentityUser<long>
{
    public string Name { get; set; }
    public List<Photo> Photos { get; set; }
    public List<AppUserRole> UserRoles { get; set; }
}

public class AppRole : IdentityRole<long>
{
    public ICollection<AppUserRole> UserRoles { get; set; }
}

public class AppUserRole : IdentityUserRole<long>
{
    public AppUser User { get; set; }
    public AppRole Role { get; set; }
}

Config:

builder.Entity<AppUser>(b =>
        {
            b.HasKey(e => e.Id);

            b.HasMany(ur => ur.UserRoles)
             .WithOne(u => u.User)
             .HasForeignKey(u => u.UserId)
             .IsRequired();
        });

builder.Entity<AppRole>(b =>
        {
            b.HasKey(e => e.Id);

            b.HasMany(ur => ur.UserRoles)
             .WithOne(u => u.Role)
             .HasForeignKey(u => u.RoleId)
             .IsRequired();
        });

builder.Entity<AppUserRole>(b =>
        {
            b.HasOne(ur => ur.User)
             .WithMany(u => u.UserRoles)
             .HasForeignKey(ur => ur.UserId);
            b.HasOne(ur => ur.Role)
             .WithMany(r => r.UserRoles)
             .HasForeignKey(ur => ur.RoleId);
        });

Query:

var users = await _userManager.Users
                              .Include(u => u.Photos)
                              .Include(u => u.UserRoles)
                              .ThenInclude(ur => ur.Role)
                              .ToListAsync();

From the query I'm expecting the list of the user with Roles. But Role list is empty. I have added roles to the user.

Note: .Include() for Photos is working fine, and it is one to many relation, but UserRoles is not working.


Solution

  • Finally, I fixed the issue.

    I replaced

    public class DataContext : IdentityDbContext<AppUser, AppRole, long>
    {
    }
    

    to

    public class DataContext : IdentityDbContext<AppUser, AppRole, long, IdentityUserClaim<long>,
        AppUserRole, IdentityUserLogin<long>, IdentityRoleClaim<long>, IdentityUserToken<long>>
    {
    }
    

    and it's working fine as I expected.