问题
How to add a fixed role (e.g. Admin) to an existing Asp.Net Mvc/Identity 2 site?
In the link
http://bitoftech.net/2015/03/11/asp-net-identity-2-1-roles-based-authorization-authentication-asp-net-web-api/, there are the following code which is exactly what I want to do. However, will the Seed function be executed since the application? (I already have some code, var lookup1 = new List<L1>{new L1 {...},...}; tableL1.ForEach(l => context.tableL1.AddOrUpdate(p=>p.Title, l)); context.SaveChanges();, in the Seed function to seed some lookup tables.). What's the right way to Add a role to an application which is already online?
// internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(AspNetIdentity.WebApi.Infrastructure.ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var user = new ApplicationUser()
{
UserName = "SuperPowerUser",
Email = "taiseer.joudeh@gmail.com",
EmailConfirmed = true,
FirstName = "Taiseer",
LastName = "Joudeh",
Level = 1,
JoinDate = DateTime.Now.AddYears(-3)
};
manager.Create(user, "MySuperP@ss!");
if (roleManager.Roles.Count() == 0)
{
roleManager.Create(new IdentityRole { Name = "SuperAdmin" });
roleManager.Create(new IdentityRole { Name = "Admin"});
roleManager.Create(new IdentityRole { Name = "User"});
}
var adminUser = manager.FindByName("SuperPowerUser");
manager.AddToRoles(adminUser.Id, new string[] { "SuperAdmin", "Admin" });
}
}
回答1:
If you want to seed the database you have to Enable-Migrations in the Package Manager Console.
I guess you have done that already since you already have the Configuration.cs file.
In the constructor of you configuration class make sure AutomaticMigrationsEnabled is set to false or your database will be recreated.
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
Now you can compile your solution and from Package Manager Console (Make sure your selecting the right project in the Default Project combo) run:
Update-Database
or
Update-Database -Verbose
if you want to collect more info.
and you should see your new data in the database.
来源:https://stackoverflow.com/questions/31553729/change-seed-method-for-an-existing-asp-net-mvc-5-identity-2-application