问题
I am using AddOrUpdate in my seed method to keep my permissions up to date, however, in the situation where the below code is updating the existing role (rather than creating it), any new Permissions I created are not being added to the role. What am I doing wrong?
foreach (KeyValuePair<string, string[]> s in new Dictionary<string, string[]>{
{"Superuser", context.Permissions.Select<Permission, string>(p=>p.Name).ToArray()},
})
{
Role r = new Role();
r.Name = s.Key;
r.Permissions = new List<Permission>();
foreach (string p in s.Value)
r.Permissions.Add(context.Permissions.Where(per => per.Name == p).First());
context.Roles.AddOrUpdate(i => i.Name, r);
}
context.SaveChanges();
回答1:
AddOrUpdate
only adds or updates the main entity, but not its relations.
So you have to do it in two steps:
- Create the
Role
, andAddOrUpdate
it. Now you can get theRoleId
(or whatever the PK is) form your added or updatedRole
. - Create the
Permissions
, and set explicitly theirRoleId
(or whatever the FK is). ThenAddOrUpdate
thePermissions
.
来源:https://stackoverflow.com/questions/23067806/addorupdate-does-not-modify-children