Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure the Users context/table?

With the new ASP.NET MVC 5 Preview released, how do I configure the Users context/table?

In MVC 4 I would just use my own User class and then point the WebSecurity initialize to it, tike this:

WebSecurity.InitializeDatabaseConnection(connectionString, "System.Data.SqlClient", userTableName, userIdColumn, userNameColumn, autoCreateTables);

I wish to add additional properties to the Users class - how?

like image 347
Martin Avatar asked Oct 04 '22 16:10

Martin


1 Answers

I think, this can solve your issue:


In Models \ IdentityModels.cs you can redefine your own User model:

public class ApplicationUser : IdentityUser
{
    /* identity field from database */
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    [Required]
    public bool Internal { get; set; }

    public string UserFullName { get; set; }

    public string UserEmail { get; set; }

    public ApplicationUser()
        : base()
    {
        Internal = false;
    }

    public ApplicationUser(string userName)
        : base(userName)
    {
        Internal = false;
    }

}

now you can change mapping of defaults AspNet tables using OnModelCreating() overridding and ToTable() methode:

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

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

        // Change the name of the table to be Users instead of AspNetUsers
        modelBuilder.Entity<IdentityUser>().ToTable("User");
        modelBuilder.Entity<ApplicationUser>().ToTable("User");

        modelBuilder.Entity<IdentityRole>().ToTable("Role");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("User_Claim");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("User_Login");
        modelBuilder.Entity<IdentityUserRole>().ToTable("User_Role");
    }
}

Finally you will see in the database the following tables: User, Role, User_Role, User_Claim, User_Login instead of AspNetUsers, AspNetRoles, AspNetUsersRoles, AspNetUsersClaims, AspNetUserLogins.

Of course the User table will contain additional fields: UserId (int identity), Internal, UserFullName and UserEmail.

like image 192
Jerzy Gebler Avatar answered Oct 12 '22 13:10

Jerzy Gebler