Reputation: 11
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
?
Upvotes: 1
Views: 2210
Reputation: 13775
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.
Upvotes: 1