Seed the database with initial Users in MVC 5

By October 16, 2014 MVC One Comment
seeddbimg1

In MVC 5 applications you may want to seed the database with initial users for various reasons. You may want default users and roles added as part of the application. In this post, we will take a look at how to  seed the database with default users.
The MVC 5 application uses ASP.Net Identity 2.0 to manage users, roles and identities. ASP.Net Identity 2.0 uses the Entity framework code first approach to create a database. To seed the database, first you need to enable migration on the database. To enable migration, in the package manager console run the command enable-migrations as shown below:

seeddbimg1

After successfully enabling migration you should find a Migrations folder in the solution explorer.
seeddbimg2

In the Configuration.cs file there is Seed method. In the Seed method you can add users to seed in the database.

seeddbimg3
There are two ways users can be added:

  1. Using the LINQ to Entity
  2. Using the UserStore

The first approach is using the entity framework LINQ to Entity. Using this approach we can add a user as follows:

In the entity framework approach you need to hash the password manually. The ASP.Net Identity provides us the PasswordHasher class to create a password hash for a given password as a string. We are using that in the above code snippet. To insert a user the AddorUpdate method is used.

The second approach to insert a user is using the UserStore. In this approach you don’t have to take care of password hashing. Using this approach we can add a user as follows:

To create a user using UserStore:

  1. Create an instance of UserStore of the type ApplicationUser and pass the data context in the constructor
  2. Create an instance of UserManager of the type ApplicationUser and pass the instance of user store in the constructor
  3. Create the user by calling Create method on the user manager instance

As the last step, run the update-database command in the package manager console.
seeddbimg4
If you get an error in the execution of update-database, make sure that Configuration.cs automatic migration is enabled.
seeddbimg5
In this way, a database can be seeded with default users. Again, the steps to seed a user are:

  • Enabling migration
  • Putting the code to insert in the seed method
  • Updating the database

Happy coding.

The following two tabs change content below.
Dhananjay Kumar is a software engineer, consultant, trainer, blogger and speaker from India. He has been a Microsoft MVP since 2010. He can be followed on twitter @debug_mode.