4 changed files with 113 additions and 6 deletions
@ -0,0 +1,25 @@ |
|||
using CellularManagement.Domain.Entities; |
|||
|
|||
namespace CellularManagement.Domain.Repositories; |
|||
|
|||
/// <summary>
|
|||
/// 用户角色仓储接口
|
|||
/// </summary>
|
|||
public interface IUserRoleRepository |
|||
{ |
|||
/// <summary>
|
|||
/// 添加用户角色关系
|
|||
/// </summary>
|
|||
/// <param name="userRole">用户角色关系实体</param>
|
|||
/// <param name="cancellationToken">取消令牌</param>
|
|||
/// <returns>添加的用户角色关系实体</returns>
|
|||
Task<UserRole> AddAsync(UserRole userRole, CancellationToken cancellationToken = default); |
|||
|
|||
/// <summary>
|
|||
/// 获取用户角色
|
|||
/// </summary>
|
|||
/// <param name="userId">用户ID</param>
|
|||
/// <param name="cancellationToken">取消令牌</param>
|
|||
/// <returns>用户角色列表</returns>
|
|||
Task<IList<string>> GetUserRolesAsync(string userId, CancellationToken cancellationToken = default); |
|||
} |
|||
@ -0,0 +1,67 @@ |
|||
using Microsoft.EntityFrameworkCore; |
|||
using CellularManagement.Domain.Entities; |
|||
using CellularManagement.Domain.Repositories; |
|||
using CellularManagement.Infrastructure.Context; |
|||
using Microsoft.Extensions.Logging; |
|||
|
|||
namespace CellularManagement.Infrastructure.Repositories; |
|||
|
|||
/// <summary>
|
|||
/// 用户角色仓储实现类
|
|||
/// </summary>
|
|||
public class UserRoleRepository : IUserRoleRepository |
|||
{ |
|||
private readonly AppDbContext _context; |
|||
private readonly IUnitOfWork _unitOfWork; |
|||
private readonly ILogger<UserRoleRepository> _logger; |
|||
|
|||
/// <summary>
|
|||
/// 初始化仓储
|
|||
/// </summary>
|
|||
/// <param name="context">数据库上下文</param>
|
|||
/// <param name="unitOfWork">工作单元</param>
|
|||
/// <param name="logger">日志记录器</param>
|
|||
public UserRoleRepository( |
|||
AppDbContext context, |
|||
IUnitOfWork unitOfWork, |
|||
ILogger<UserRoleRepository> logger) |
|||
{ |
|||
_context = context; |
|||
_unitOfWork = unitOfWork; |
|||
_logger = logger; |
|||
} |
|||
|
|||
/// <inheritdoc />
|
|||
public async Task<UserRole> AddAsync(UserRole userRole, CancellationToken cancellationToken = default) |
|||
{ |
|||
try |
|||
{ |
|||
await _context.UserRoles.AddAsync(userRole, cancellationToken); |
|||
await _unitOfWork.SaveChangesAsync(cancellationToken); |
|||
return userRole; |
|||
} |
|||
catch (Exception ex) |
|||
{ |
|||
_logger.LogError(ex, "添加用户角色关系时发生错误,用户ID:{UserId},角色ID:{RoleId}", |
|||
userRole.UserId, userRole.RoleId); |
|||
throw; |
|||
} |
|||
} |
|||
|
|||
/// <inheritdoc />
|
|||
public async Task<IList<string>> GetUserRolesAsync(string userId, CancellationToken cancellationToken = default) |
|||
{ |
|||
try |
|||
{ |
|||
return await _context.UserRoles |
|||
.Where(ur => ur.UserId == userId) |
|||
.Select(ur => ur.Role.Name) |
|||
.ToListAsync(cancellationToken); |
|||
} |
|||
catch (Exception ex) |
|||
{ |
|||
_logger.LogError(ex, "获取用户角色时发生错误,用户ID:{UserId}", userId); |
|||
throw; |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue