I'm not exactly sure why my Seed method is throwing an exception.
Here is my code:
//Roles
var roles = new List<Role>
{
new Role {RoleName = "Admin"},
new Role {RoleName = "SuperAdmin"}
};
roles.ForEach(s => context.Roles.AddOrUpdate(p => p.RoleName, s));
context.SaveChanges();
//Adds the 2 superadmins from AD to DB
Credentials.GetUserByUsername(context, "credentials1");
Credentials.GetUserByUsername(context, "credentials2");
context.SaveChanges();
//Add the superadmins to a List
var superAdmins = new List<User>();
User admin1 = context.Users.Where(p => p.Username == "credentials1").FirstOrDefault();
User admin2 = context.Users.Where(p => p.Username == "crendetials2").FirstOrDefault();
superAdmins.Add(admin1);
superAdmins.Add(admin2);
//Find the SuperAdmin role in DB
Role superAdminRole = context.Roles.Where(p => p.RoleName == "SuperAdmin").FirstOrDefault();
//Add the role to each user
foreach (User user in superAdmins)
{
if (user != null)
{
superAdminRole.Users.Add(user); <---- This is throwing the exception
context.SaveChanges();
}
}
superAdminRole.Users.Add(user) is throwing the exception. I can see when debugging that both users and roles are found so I'm not sure why I'm getting the exception.
Is it too early to do this operation? I assumed my context was able to handle this operation at this point since both users and roles are in the DB.
One last detail: if I stop debugging at this point and run the application a second time, I don't get the exception and Roles are properly assigned. I would like to avoid having to run the Seed method twice though.