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?
"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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With