重命名表后出现IdentityUserRole表列重复、无法删除主键问题求助
Hey there, let's work through this IdentityUserRole problem you're hitting. The issue is likely rooted in how Entity Framework handles the default many-to-many join table for user-role associations, especially when you're customizing table names without explicitly configuring this specific entity.
Why This Happens
By default, IdentityUserRole is a join table with a composite primary key made up of UserId and RoleId. When you don't explicitly map this entity in your OnModelCreating method, EF might still use its default conventions alongside your custom table renames—leading to duplicate columns and conflicts when trying to modify the primary key.
Step-by-Step Fix
Add an explicit configuration for IdentityUserRole in your OnModelCreating method to define the table name and its composite primary key. Here's how to update your code:
protected override void OnModelCreating(DbModelBuilder builder) { builder.Conventions.Remove<PluralizingTableNameConvention>(); // Existing configurations builder.Entity<IdentityUserClaim>().ToTable("UserClaim").HasKey<int>(r => r.Id); builder.Entity<IdentityUserLogin>().ToTable("UserLogin").HasKey<string>(l => l.UserId); builder.Entity<IdentityRole>().ToTable("Role").HasKey<string>(r => r.Id); // Add this configuration for IdentityUserRole builder.Entity<IdentityUserRole<string>>() .ToTable("UserRole") // Rename the join table to your preferred name .HasKey(ur => new { ur.UserId, ur.RoleId }); // Explicitly set the composite primary key }
Key Notes
- Composite Primary Key:
IdentityUserRolerelies on bothUserIdandRoleIdas its primary key (it's a many-to-many join table). You can't use a single-field key here—this is why you were having trouble deleting the primary key before. - Consistent Generic Types: Make sure the generic type for
IdentityUserRolematches the types you're using for yourIdentityUserandIdentityRole(e.g., if you're usingstringfor IDs, useIdentityUserRole<string>). - Clean Up Migrations: After updating the configuration, you'll need to create a new migration to apply these changes to your database. Run
Add-Migration FixUserRoleTable(or a name of your choice) followed byUpdate-Databaseto sync the schema.
This should resolve the duplicate column issue and properly configure the primary key for your renamed UserRole table.
内容的提问来源于stack exchange,提问作者John Nyingi

