Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Seed Users and Roles

I have been playing about with the new MVC 5, I have a few models, controller and views setup using code first migrations.

My question is how do I seed users and roles? I currently seed some reference data in my Seed method in Configuration.cs. But it looks to me that the user and roles tables are not created until something first hits the AccountController.

I currently have two connection strings so I can separate my data from my authentication into different databases.

How can I get the user, roles, etc tables populate along with my others? And not when the account controller is hit?

like image 875
MrBeanzy Avatar asked Oct 09 '13 19:10

MrBeanzy


People also ask

What are seed users?

"Seed Users Provided as Seed Data": Provides information on the seed data provided with Siebel Business Applications in general. "Seed User Modifications for Siebel Financial Services Applications": Provides information on the seed data provided with Siebel Financial Services applications.

What is seeding in MVC?

Usually, we don't use "Database Migrations" in our normal application development and for this, the Entity Framework has the Database "Seed" Method that allows you to seed some dummy data in the database for testing purposes and this could be used in MVC, ASP.NET Web Forms, Windows Form apps, etc.

How do you seed a role in identity?

You can seed Users and Roles in OnModelCreating() method inside IdentityDbContext. cs file as shown below. Notice that the keys have to be predefined to avoid seeding new users and roles everytime this method is executed. This is the correct answer for .

What is seeding in Entity Framework?

The Seed method takes the database context object as an input parameter, and the code in the method uses that object to add new entities to the database. To seed data into your database, you need to override the Seed method.


1 Answers

Here is example of usual Seed approach:

protected override void Seed(SecurityModule.DataContexts.IdentityDb context) {     if (!context.Roles.Any(r => r.Name == "AppAdmin"))     {         var store = new RoleStore<IdentityRole>(context);         var manager = new RoleManager<IdentityRole>(store);         var role = new IdentityRole { Name = "AppAdmin" };          manager.Create(role);     }      if (!context.Users.Any(u => u.UserName == "founder"))     {         var store = new UserStore<ApplicationUser>(context);         var manager = new UserManager<ApplicationUser>(store);         var user = new ApplicationUser {UserName = "founder"};          manager.Create(user, "ChangeItAsap!");         manager.AddToRole(user.Id, "AppAdmin");     } } 

I used package-manager "update-database". DB and all tables were created and seeded with data.

like image 138
Valin Avatar answered Sep 22 '22 02:09

Valin