由于没有人回答过您的问题,因此我会添加一些代码来说明如何在迁移时从 Seed 方法执行此操作。此代码用于在数据库中为具有管理员角色的初始用户播种。在我的情况下,只有“管理员”用户可以向站点添加新用户。
protected override void Seed(PerSoft.Marketing.Website.Models.ApplicationDbContext context)
{
const string defaultRole = "admin";
const string defaultUser = "someUser";
// This check for the role before attempting to add it.
if (!context.Roles.Any(r => r.Name == defaultRole))
{
context.Roles.Add(new IdentityRole(defaultRole));
context.SaveChanges();
}
// This check for the user before adding them.
if (!context.Users.Any(u => u.UserName == defaultUser))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser { UserName = defaultUser };
manager.Create(user, "somePassword");
manager.AddToRole(user.Id, defaultRole);
}
else
{
// Just for good measure, this adds the user to the role if they already
// existed and just weren't in the role.
var user = context.Users.Single(u => u.UserName.Equals(defaultUser, StringComparison.CurrentCultureIgnoreCase));
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
manager.AddToRole(user.Id, defaultRole);
}
}