I have an ASP.NET MVC 5 project (razor engine) which has Identity 2.0 with Individual User Accounts. I am using Visual Studio Professional 2013
I have not found any clea
EF has two different Seed methods. One that is used with database initializers and another that is used with Migrations. Since you've enabled Migrations, I'll describe how to do this with the Migrations Seed method here...
First of all, even though you've enabled Migrations, by default EF still uses the CreateDatabaseIfNotExists database initializer. Which means when you run your app, the first time the ApplicationDbContext is accessed, the initializer is called and it'll create the database tables from your Code First mappings if the tables don't exist already. You're not seeing the schema created because you probably haven't accessed the db context. In a new web app, this is typically triggered the first time you register a user or try to log in.
To seed the ASP.NET Identity tables, there are two things you need to do. The first is to add seed logic to the Seed method in Configuration.cs. The second is to trigger update-database... either by running it in the Package Manager Console or by using the MigrateDatabaseToLatestVersion database initializer.
Here's an example of what you can put into the Seed method to create a role and a user...
public Configuration()
{
AutomaticMigrationsEnabled = true;
// ...
}
protected override void Seed(MyProject.Web.Models.ApplicationDbContext context)
{
if (!context.Roles.Any())
{
var roleStore = new RoleStore(context);
var roleManager = new RoleManager(roleStore);
var role = new IdentityRole{
Name = "Administrator"
};
roleManager.Create(role);
}
if (!context.Users.Any())
{
var userStore = new UserStore(context);
var userManager = new ApplicationUserManager(userStore);
var user = new ApplicationUser {
Email = "foo@bar.com",
UserName = "SuperUser"
};
userManager.Create(user, "MySecretPassword1234");
userManager.AddToRole(user.Id, "Administrator");
}
}
After this is done, you can run Update-Database from the Package Manager Console to migrate the database to the latest schema and run the Seed method.
Or you can change EF to use the MigrateDatabaseToLatestVersion initializer by modifying the context in IdentityModels.cs...
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion());
}
}
Now when you run the application, the first time the database context is used it'll run update-database and seed it.