You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重命名表后出现IdentityUserRole表列重复、无法删除主键问题求助

Fixing IdentityUserRole Duplicate Columns & Primary Key Issues

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: IdentityUserRole relies on both UserId and RoleId as 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 IdentityUserRole matches the types you're using for your IdentityUser and IdentityRole (e.g., if you're using string for IDs, use IdentityUserRole<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 by Update-Database to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:09:15