0

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

Can anyone explain what happens here and what I can do to fix this problem? I am sorry if the question is duplicate, I tried to search from google and stackoverflow, but cant find an answer.

Lord Yggdrasill
  • 3,197
  • 4
  • 26
  • 42

2 Answers2

1

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

0

As I can only guess IdentityUserRole has two fields UserId and RoleId. Since one user can have several roles, RoleId can be repeating many times, so it can be a primary key. you can only create a composite key

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

or you can add primary key column Id to this table

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

Serge
  • 40,935
  • 4
  • 18
  • 45