新增这样做是可以新增 但下面修改就不行
public void Add(Role role, long[] userIds, long[] functionIds)
{
if (Exists(role.RoleName)) throw new BusinessRuleValidationException("角色名已存在");
if (userIds != null && userIds.Length > 0)
role.Users = _userRepository.GetAll().Where(t => userIds.Contains(t.Id)).ToList();
if (functionIds != null && functionIds.Length > 0)
role.Functions = _functionRepository.GetAll().Where(t => functionIds.Contains(t.Id)).ToList();
_roleRepository.Insert(role);
this._unitOfWork.Commit();
}
但是这样修改就不行了
public void Modify(Role role, long[] userIds, long[] functionIds)
{
if (Exists(role.RoleName, role.Id)) throw new BusinessRuleValidationException("角色名已存在");
var roleData = _roleRepository.GetAll().Include(t => t.Users).Include(t => t.Functions).FirstOrDefault(t => t.Id == role.Id);
roleData.RoleName = role.RoleName.Trim();
roleData.Description = role.Description;
roleData.Users.Clear();
roleData.Functions.Clear();
if (userIds != null && userIds.Length > 0)
_userRepository.GetAll().Where(t => userIds.Contains(t.Id)).ToList().ForEach(x => roleData.Users.Add(x));
if (functionIds != null && functionIds.Length > 0)
_functionRepository.GetAll().Where(t => functionIds.Contains(t.Id)).ToList().ForEach(x => roleData.Functions.Add(x));
_roleRepository.Update(roleData);
this._unitOfWork.Commit();
}
这个是修改方法
public virtual TEntity Update(TEntity entity)
{
_entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
return entity;
}