Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddOrUpdate does not modify children

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();
like image 630
pquest Avatar asked Jan 21 '26 23:01

pquest


1 Answers

AddOrUpdate only adds or updates the main entity, but not its relations.

So you have to do it in two steps:

  1. Create the Role, and AddOrUpdate it. Now you can get the RoleId (or whatever the PK is) form your added or updated Role.
  2. Create the Permissions, and set explicitly their RoleId (or whatever the FK is). Then AddOrUpdate the Permissions.
like image 62
JotaBe Avatar answered Jan 24 '26 19:01

JotaBe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!