Search code examples
entity-frameworkasp.net-identityuser-roles

Entity Framework Identity - Duplicate UserId in UserLogin


I'm extending all the Identity tables. Every thing is working well, but in the database UserLogin gets an extra column named User_Id.

        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
        modelBuilder.Entity<Role>().ToTable("Role");

        modelBuilder.Entity<UserLogin>().HasKey<int>(ul => ul.UserId);
        modelBuilder.Entity<Role>().HasKey<int>(r => r.Id);
        modelBuilder.Entity<UserRole>().HasKey(ur => new { ur.RoleId, ur.UserId });

        modelBuilder.Entity<UserRole>()
            .HasRequired(ur => ur.User)
            .WithMany(u => u.UserRoles)
            .HasForeignKey(ur => ur.UserId)
            .WillCascadeOnDelete(false);


public class UserLogin : IdentityUserLogin<int>
{
}

The UserLogin table looks like this: UserId | LoginProvider | ProviderKey | User_Id

I suspect that it have something to do with HasKey. If I remove that row I get an error saying that UserLogin needs an id, but I can then add public int Id... to the UserLogin class. The table will then look like this: Id | UserId | LoginProvider | ProviderKey

Does any one have a clue where this extra user id is coming from and how I can get rid of it?


Solution

  • You asked this ages ago, but I have just seen it. Just incase you never answered it, you need to change your UserLogin.HasKey to this:

    modelBuilder.Entity<UserLogin>().HasKey(m => new { m.UserId, m.ProviderKey });
    

    If you just have the UserId as the primary key, then you are suggesting a one to one relationship (because the UserId has to be unique) which is not right. Once you have changed to include the provider key, then you can do this:

    modelBuilder.Entity<User>().HasMany(m => m.Logins).WithRequired().HasForeignKey(m => m.UserId);
    

    And then you will have your table set up correctly.