Ingmar
Ingmar

Reputation: 1447

How can I avoid ASP.NET Identity from adding this extra field?

I have a new MVC5 project with ASP.NET Identity 2.0 and EF 6.1.1.

I added my own ApplicationUser (based on built-in IdentityUser). This is how my DbContext is created.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

When the database is created I have tables like AspNetUsers, AspNetUserRoles, AspNetUserClaims, and AspNetUserLogins. Then I added OnModelCreating() with just the most basic statements.

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
    }

As soon as I add OnModelCreating(), the identity tables are automatically renamed to ApplicationUsers, IdentityUserRoles, IdentityUserClaims, and IdentityUserLogins. That's fine with me (and I know how to rename them).

But what I don't like: All of a sudden, IdentityUserRoles, IdentityUserClaims, and IdentityUserLogins have an extra field called "ApplicationUser_Id". The original "AspNetXXX" tables didn't have such a field.

Why is that? And is there anything I can do in order to avoid this?

Upvotes: 1

Views: 260

Answers (2)

Proneet Ray
Proneet Ray

Reputation: 63

As mentioned by Matt Lassam-Jones

worked for me also and Thank You.

public class NebulaContext : IdentityDbContext<ApplicationUser>
    {
        public NebulaContext()
            : base("Name=MyEntity", throwIfV1Schema: false)
        {

        }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {         
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); //Optional
                modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();//Optional
                modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); //Optional
                base.OnModelCreating(modelBuilder);
    }
}

Upvotes: 1

Matt Lassam-Jones
Matt Lassam-Jones

Reputation: 171

You need to call base.OnModelCreating. There are a number of additional things OnModelCreating does in IdentityDbContext that you may be missing without calling it - the default names of the tables being one of them.

Its best to call it first, then apply your own changes afterwards.

Upvotes: 2

Related Questions