修复用户角色替换的软删除冲突
This commit is contained in:
@@ -61,19 +61,40 @@ public sealed class EfUserRoleRepository(IdentityDbContext dbContext) : IUserRol
|
||||
.Where(x => x.TenantId == tenantId && x.UserId == userId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
// 3. 清空并保存
|
||||
dbContext.UserRoles.RemoveRange(existing);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
// 3. 去重并构建目标集合
|
||||
var targetRoleIds = roleIds.Distinct().ToArray();
|
||||
var targetRoleSet = targetRoleIds.ToHashSet();
|
||||
var existingRoleMap = existing.ToDictionary(x => x.RoleId);
|
||||
|
||||
// 4. 构建新映射
|
||||
var toAdd = roleIds.Distinct().Select(roleId => new UserRole
|
||||
// 4. 同步现有映射状态(软删除或恢复)
|
||||
foreach (var mapping in existing)
|
||||
{
|
||||
TenantId = tenantId,
|
||||
UserId = userId,
|
||||
RoleId = roleId
|
||||
});
|
||||
if (targetRoleSet.Contains(mapping.RoleId))
|
||||
{
|
||||
if (mapping.DeletedAt.HasValue)
|
||||
{
|
||||
mapping.DeletedAt = null;
|
||||
mapping.DeletedBy = null;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!mapping.DeletedAt.HasValue)
|
||||
{
|
||||
dbContext.UserRoles.Remove(mapping);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 补齐新增角色映射
|
||||
var toAdd = targetRoleIds
|
||||
.Where(roleId => !existingRoleMap.ContainsKey(roleId))
|
||||
.Select(roleId => new UserRole
|
||||
{
|
||||
TenantId = tenantId,
|
||||
UserId = userId,
|
||||
RoleId = roleId
|
||||
});
|
||||
|
||||
// 5. 批量新增并保存
|
||||
await dbContext.UserRoles.AddRangeAsync(toAdd, cancellationToken);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user