Search code examples
c#asp.netasp.net-mvcentity-frameworkasp.net-identity

ASP.NET MVC Creating User: Multiplicity is not valid


I tried to change the table names for ASP.NET MVC identity user (since I am working with an existing database), this code was added to the 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);;
}

When testing user registration however, I got this weird error:

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'.

What is happening here, and what I can do to fix this problem? I tried to search from Google and Stack Overflow, but can't find an answer.


Solution

  • If You want the same columns just do this, reference to 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");
    

    Or if you want change a specific columns

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

    Regards