ASP.NET MVC 创建用户:多重性无效

ASP.NET MVC Creating User: Multiplicity is not valid

我试图更改 table ASP.NET MVC 身份用户的名称(因为我正在使用现有数据库),此代码已添加到 identitymodel.cs:

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<IdentityUser>().ToTable("Web_Users").HasKey(x => x.Id);
    modelBuilder.Entity<ApplicationUser>().ToTable("Web_Users").HasKey(x => x.Id);
    modelBuilder.Entity<IdentityUserRole>().ToTable("Web_UserRoles").HasKey(x => x.RoleId);
    modelBuilder.Entity<IdentityUserLogin>().ToTable("Web_UserLogins").HasKey(x => x.UserId);
    modelBuilder.Entity<IdentityUserClaim>().ToTable("Web_UserClaims").HasKey(x => x.Id);
    modelBuilder.Entity<IdentityRole>().ToTable("Web_Roles").HasKey(x => x.Id);;
}

然而,在测试用户注册时,我遇到了这个奇怪的错误:

One or more validation errors were detected during model generation: IdentityRole_Users_Target: : Multiplicity is not valid in Role 'IdentityRole_Users_Target' in relationship 'IdentityRole_Users'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.

任何人都可以解释这里发生了什么以及我可以做些什么来解决这个问题吗?很抱歉,如果问题重复,我尝试从 google 和 Whosebug 搜索,但找不到答案。

我只能猜测 IdentityUserRole 有两个字段 UserId 和 RoleId。由于一个用户可以有多个角色,RoleId可以重复多次,所以可以作为主键。你只能创建一个组合键

 modelBuilder.Entity<IdentityUserRole>().ToTable("Web_UserRoles").HasKey(x => 
 new{x.UserId, x.RoleId});

或者您可以将主键列 ID 添加到此 table

modelBuilder.Entity<IdentityUserRole>().ToTable("Web_UserRoles").HasKey(x => x.Id);

如果你想要相同的列就这样做,参考Solution

    modelBuilder.Entity<ApplicationUser>().ToTable("Web_Users");
    modelBuilder.Entity<IdentityRole>().ToTable("Web_Roles");
    modelBuilder.Entity<IdentityUserRole>().ToTable("Web_UserRoles");
    modelBuilder.Entity<IdentityUserClaim>().ToTable("Web_UserClaims");
    modelBuilder.Entity<IdentityUserLogin>().ToTable("Web_UserLogins");

或者如果您想更改特定列

modelBuilder.Entity<ApplicationUser>().ToTable("Web_Users").Property(p => p.Id).HasColumnName("User_Id");

此致