Пример #1
0
 public int AddPowersOfRole(long roleId, List<long> powerIds)
 {
     foreach (long powerId in powerIds)
     {
         RolePower rolePower = new RolePower()
         {
             // Id
             RoleId = roleId,
             PowerId = powerId,
         };
         dbContext.RolePowers.Add(rolePower);
         dbContext.Entry(rolePower).State = EntityState.Added;
     }
     return dbContext.SaveChanges();
 }
Пример #2
0
        /// <summary>
        /// 新增角色时,分配权限
        /// </summary>
        public int AddRole(Role role, List<long> powerIds)
        {
            CheckRoleNotNull(role);

            dbContext.Roles.Add(role);
            dbContext.Entry(role).State = EntityState.Added;         // 新增角色

            foreach (long powerId in powerIds)
            {
                RolePower rp = new RolePower()
                {
                    // Id
                    RoleId = role.Id,
                    PowerId = powerId,
                };
                dbContext.RolePowers.Add(rp);
                dbContext.Entry(rp).State = EntityState.Added;       // 分配权限
            }
            return dbContext.SaveChanges();
        }
Пример #3
0
        /// <summary>
        /// role不能为null,且role.Id必须大于0。 
        /// 若计算得出role.Id没有对应的数据, 抛异常
        /// </summary>
        public int UpdateRole(Role role, List<long> powerIds)
        {
            CheckRoleNotNull(role);
            CheckRoleIdGreatThan0(role.Id);
            Role r = GetRole(new Role() { Id = role.Id, });
            CheckRoleNotNull(r);

            foreach (var field in typeof(Role).GetProperties())     // 修改角色信息
            {
                field.SetValue(r, field.GetValue(role));
            }
            dbContext.Entry(r).State = EntityState.Modified;

            var oldrps = from RolePower in dbContext.RolePowers     // 删除旧权限
                         where RolePower.RoleId == role.Id
                         select RolePower;
            foreach (RolePower rp in oldrps)
            {
                dbContext.Entry(rp).State = EntityState.Deleted;
            }

            foreach (long powerId in powerIds)                      // 新增权限
            {
                RolePower rp = new RolePower()
                {
                    // Id
                    RoleId = role.Id,
                    PowerId = powerId,
                };
                dbContext.RolePowers.Add(rp);
                dbContext.Entry(rp).State = EntityState.Added;
            }
            return dbContext.SaveChanges();
        }