Search code examples
c#many-to-manyasp.net-core-5.0ef-core-5.0

How to use Implicit Many to Many between IdentityUser and IdentityRole in ASP.NET Core 5


I have these 2 entities.

public class ApplicationUser : IdentityUser<int>
    {
        public int DepartmentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string NationalCode { get; set; }
        public DateTimeOffset DateCreated { get; set; } = DateTimeOffset.Now;
        public DateTimeOffset DateModified { get; set; } = DateTimeOffset.Now;
        public CorporateTitle CorporateTitle { get; set; }

        public Department Department { get; set; }
        public ICollection<ApplicationRole> Roles { get; set; } //* instead of IdetityUserRole

  public class ApplicationRole : IdentityRole<int>
    {
        public string DisplayName { get; set; }
        public string Description { get; set; }
        public ICollection<ApplicationUser> Users { get; set; } //* instead of IdetityUserRole

    }

I want to Customize these 2 entities for example overriding navigation properties. I don't want to use IdentityUserRole Class for many to many relationship between these classes.

How should I write a configuration for this type of implicit Many to Many in Identity Core?

 builder.Entity<ApplicationUser>()
                .HasMany(appUser => appUser.Roles)
                .WithMany(role => role.Users)
                .UsingEntity<>(); // here I don't know how to config this relationship.

Solution

  • this is the configuration need for this scenario. (Skip Navigation EF Core 5)

     builder.Entity<ApplicationUser>()
                            .HasMany(u => u.Roles)
                            .WithMany(r => r.Users)
                            .UsingEntity<IdentityUserRole<int>>
                            (au => au.HasOne<ApplicationRole>().WithMany(role => role.UserRoles).HasForeignKey(u=> u.RoleId),
                            au => au.HasOne<ApplicationUser>().WithMany(user => user.UserRoles).HasForeignKey(r=> r.UserId));
    
    

    for complete source code : https://github.com/ArminShoeibi/ImplicitManyToManyIdentityCore