Home > Blockchain >  ASP.NET Core Identity Added extra foreign key in AspNetUserRoles
ASP.NET Core Identity Added extra foreign key in AspNetUserRoles

Time:05-12

There are two extra foreign keys (TheUsrId, TheRoleId) in AspNetUserRoles table as you can see in the picture below. enter image description here

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.

CodePudding user response:

ASP.NET Core Identity creates its own relationships and columns by itself in AppRole and AppUserRole when you don't write anything in those classes.

In AppUserRole , when you create TheUser and TheRole properties, entity framework adds "Id" at the end of it and creates a new relationship. So this is the rule of entity framework.

You should remove them all and try to see the reason why.

CodePudding user response:

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.

  • Related