There are two extra foreign keys (TheUsrId, TheRoleId) in AspNetUserRoles table as you can see in the picture below.
And here is the configuration:
public class AppUser : IdentityUser<int>
{
... // other properties
public ICollection<AppUserRole> TheUserRolesList { get; set; }
}
public class AppRole : IdentityRole<int>
{
public ICollection<AppUserRole> TheUserRolesList { get; set; }
}
public class AppUserRole : IdentityUserRole<int>
{
public AppUser TheUser { get; set; }
public AppRole TheRole { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AppUser>(b =>
{
b.HasMany(x => x.TheUserRolesList)
.WithOne(x => x.TheUser)
.HasForeignKey(x => x.UserId)
.IsRequired();
});
modelBuilder.Entity<AppRole>(b =>
{
b.HasMany(e => e.UserRoles)
.WithOne(e => e.Role)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
});
base.OnModelCreating(modelBuilder);
}
I've tried several ways such as this and changed the name of TheUser
to User
but Eventually, I had UserId1
as a foreign key.
Finally, I noticed that it was a bug in EntityFrameworkCore version 5.0.4 and After Updating to 5.0.17 the problem was solved.