I found this piece does not work properly:
protected override void Seed(PintxoLista.Models.ApplicationDbContext context)
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
if (!context.Roles.Any(r => r.Name == "WeddingGuest"))
{
var role = new IdentityRole { Name = "WeedingGuest" };
manager.Create(role);
}
if (!context.Roles.Any(r => r.Name == "BrideGroom"))
{
var role = new IdentityRole { Name = "BrideGroom" };
manager.Create(role);
}
if (System.Diagnostics.Debugger.IsAttached == false)
{
System.Diagnostics.Debugger.Launch();
}
context.Users.AddOrUpdate(i => i.Id,
new ApplicationUser
{
Id = "1",
UserName = "han",
Email = "hansolo1@rebels.com",
PasswordHash = new PasswordHasher().HashPassword("1"),
SecurityStamp = string.Empty
},
new ApplicationUser
{
Id = "2",
UserName = "lando",
Email = "lando@rebels.com",
PasswordHash = new PasswordHasher().HashPassword("1"),
SecurityStamp = string.Empty
});
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
userManager.AddToRole("1", "WeedingGuest");
userManager.AddToRole("2", "BrideGroom");
}
The roles are created but the users are not and then the first AddToRole
fails. Instead, if the users are add (or updated) to the database first then it works fine.
protected override void Seed(PintxoLista.Models.ApplicationDbContext context)
{
context.Users.AddOrUpdate(i => i.Id,
new ApplicationUser
{
Id = "1",
UserName = "han",
Email = "hansolo1@rebels.com",
PasswordHash = new PasswordHasher().HashPassword("1"),
SecurityStamp = string.Empty
}, new ApplicationUser
{
Id = "2",
UserName = "lando",
Email = "lando@rebels.com",
PasswordHash = new PasswordHasher().HashPassword("1"),
SecurityStamp = string.Empty
});
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
if (!context.Roles.Any(r => r.Name == "WeddingGuest"))
{
var role = new IdentityRole { Name = "WeedingGuest" };
manager.Create(role);
}
if (!context.Roles.Any(r => r.Name == "BrideGroom"))
{
var role = new IdentityRole { Name = "BrideGroom" };
manager.Create(role);
}
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
userManager.AddToRole("1", "WeedingGuest");
userManager.AddToRole("2", "BrideGroom");
}
Can anyone explain this apparently strange behaviour? Why the users must be created first? Thank you!!