AddOrUpdate不修改子级 [英] AddOrUpdate does not modify children

查看:86
本文介绍了AddOrUpdate不修改子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的seed方法中使用AddOrUpdate来使我的权限保持最新,但是,在以下代码更新现有角色(而不是创建它)的情况下,我创建的任何新权限都没有添加到角色.我在做什么错了?

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();

推荐答案

AddOrUpdate仅添加或更新主要实体,但不添加或更新其关系.

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

所以您必须分两个步骤进行操作:

So you have to do it in two steps:

  1. 创建Role,然后AddOrUpdate.现在,您可以从添加或更新的Role中获取RoleId(或任何PK).
  2. 创建Permissions,并显式设置其RoleId(或FK是什么).然后AddOrUpdate Permissions.
  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.

这篇关于AddOrUpdate不修改子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆