I have 2 entities – Roles and Administrators. Roles has two values – Search Admin and Super Admin. I have created these using EF Code First model. Now I am trying to seed values to the database and I add the roles first:
private static void SeedRoles(PayByPhoneDbContext context)
{
var roles = new List<Role> {new Role {Name = "Search Administrator"}, new Role {Name = "Super Administrator"}};
roles.ForEach(role => context.Roles.Add(role));
}
Now I want to use one of the roles created above to be used while adding administrators:
private void SeedAdministrators(PayByPhoneDbContext context)
{
var administrators = new List<Administrator>{new Administrator {Email = "a@a.com", Name = "Achinth Gurkhi", Password = "hello", Active = true, Role = ? }}
}
How do I set Role here? Should I say Role = new Role { Name = "Super Administrator" } or search for Role inserted by SeedRoles method? Also, how do I search for an existing role using the context?
If both methods are called before you execute
SaveChangeson your context you must use the same role instance you created inSeedRolesotherwise you will create anotherRolewith the same name. You must either pass created role / roles toSeedAdministrators(which is correct approach) or you can try to querycontext.Roles.Local.Where(r => r.Name = "...")and search for the role.