The following code does not work, and I can't explain why... My user manager is causing significant distress in that it creates users and roles just fine but when I run this code userManager.IsInRole is always returning false, so the second time I run my seed I am hitting errors because it is trying to create the record despite the fact it already exists!
Please note that this is occurring when I am running update-database against my migrations project, is the fact this is a non ASP project causing issues, if so why? shouldn't an error be thrown.
This is the first project I have used Identity and although when it works it seems good, there is very little up to date good quality documentation available, so if anyone has any sources for this I would be grateful.
public void Run(BlogContext blogContext)
{
var userStore = new UserStore<User>((BlogContext) blogContext);
var userManager = new UserManager<User>(userStore);
var userRoles = new List<UserRole>()
{
new UserRole() {Username = "SysAdmin@test.com", Role = "SysAdmin"},
new UserRole() {Username = "testAdmin@test.com", Role = "Admin"},
new UserRole() {Username = "testAuthor@test.com", Role = "Author"}
};
foreach (var userRole in userRoles)
{
var userId = userManager.FindByName(userRole.Username).Id;
if (!userManager.IsInRole(userId, userRole.Role))
userManager.AddToRole(userId, userRole.Role);
}
blogContext.SaveChanges();
}