简体   繁体   中英

ASP.NET MVC5 Identity using custom table structure

How can I use ASP.NET Identity with custom table structure as User ( UserId , Password ) and UserRole ( UserId,IsAdmin,IsNormalUser,IsManager ) With MVC 5? I don't want to use all default tables like AspNetUsers , AspNetRoles , AspNetUserClaims , AspNetUserRoles , AspNetUserLogins ?

Use the OnModelCreating event to map the tables and/or columns to your own schema as I have done in this StackOverflow question .

This will look something like-

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

    var user = modelBuilder.Entity<IdentityUser>().HasKey(u => u.Id).ToTable("User", "Users"); //Specify our our own table names instead of the defaults

    user.Property(iu => iu.Id).HasColumnName("UserId");
    user.Property(iu => iu.UserName).HasColumnName("UserName");
    user.Property(iu => iu.PasswordHash).HasColumnName("Password");
    user.Ignore(iu => iu.Email);
    user.Ignore(iu => iu.EmailConfirmed);
    user.Ignore(iu => iu.PhoneNumber);
    user.Ignore(iu => iu.PhoneNumberConfirmed);
    user.Ignore(iu => iu.AccessFailedCount);
    user.Ignore(iu => iu.LockoutEnabled);
    user.Ignore(iu => iu.LockoutEndDateUtc);
    user.Ignore(iu => iu.SecurityStamp);
    user.Ignore(iu => iu.TwoFactorEnabled);

    user.HasMany(u => u.Roles).WithRequired().HasForeignKey(ur => ur.UserId);

    user.Ignore(iu => iu.Logins);
    user.Ignore(iu => iu.Claims);

    modelBuilder.Ignore<IdentityUserClaim)();

    modelBuilder.Ignore<IdentityUserLogin>();

...

}

The key parts of the fluent API here are the ToTable([TableName], [SchemaName]) and HasColumnName([ColumnName])

This can be adapted to either create the table for you using standard Entity Framework Code First, or map to an existing database or one you create manually using SQL scripts.

See Code First to a New Database for more on Code First (including Fluent API mapping)

As you are wanting to ignore properties of the DbContext classes and exclude some DbContext classes from being mapped altogether you will want to use the .Ignore() extension method for unmapped properties and .Ignore<T>() extension method of the model builder for the classes.

These properties (and collections) will still exist in memory, but will not be persisted to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM