feat(console): add RoleRepository

This commit is contained in:
Sam 2026-02-05 14:15:20 +08:00
parent 75b161bc60
commit 134647d6c9
2 changed files with 101 additions and 0 deletions

View File

@ -0,0 +1,15 @@
using Fengling.AuthService.Models;
namespace Fengling.Console.Repositories;
public interface IRoleRepository
{
Task<ApplicationRole?> GetByIdAsync(long id);
Task<ApplicationRole?> GetByNameAsync(string name);
Task<IEnumerable<ApplicationRole>> GetAllAsync();
Task<IEnumerable<ApplicationRole>> GetPagedAsync(int page, int pageSize, string? name = null, string? tenantId = null);
Task<int> CountAsync(string? name = null, string? tenantId = null);
Task AddAsync(ApplicationRole role);
Task UpdateAsync(ApplicationRole role);
Task DeleteAsync(ApplicationRole role);
}

View File

@ -0,0 +1,86 @@
using Fengling.AuthService.Data;
using Fengling.AuthService.Models;
using Microsoft.EntityFrameworkCore;
namespace Fengling.Console.Repositories;
public class RoleRepository : IRoleRepository
{
private readonly ApplicationDbContext _context;
public RoleRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<ApplicationRole?> GetByIdAsync(long id)
{
return await _context.Roles.FindAsync(id);
}
public async Task<ApplicationRole?> GetByNameAsync(string name)
{
return await _context.Roles.FirstOrDefaultAsync(r => r.Name == name);
}
public async Task<IEnumerable<ApplicationRole>> GetAllAsync()
{
return await _context.Roles.ToListAsync();
}
public async Task<IEnumerable<ApplicationRole>> GetPagedAsync(int page, int pageSize, string? name = null, string? tenantId = null)
{
var query = _context.Roles.AsQueryable();
if (!string.IsNullOrEmpty(name))
{
query = query.Where(r => r.Name != null && r.Name.Contains(name));
}
if (!string.IsNullOrEmpty(tenantId))
{
query = query.Where(r => r.TenantId.ToString() == tenantId);
}
return await query
.OrderByDescending(r => r.CreatedTime)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
}
public async Task<int> CountAsync(string? name = null, string? tenantId = null)
{
var query = _context.Roles.AsQueryable();
if (!string.IsNullOrEmpty(name))
{
query = query.Where(r => r.Name != null && r.Name.Contains(name));
}
if (!string.IsNullOrEmpty(tenantId))
{
query = query.Where(r => r.TenantId.ToString() == tenantId);
}
return await query.CountAsync();
}
public async Task AddAsync(ApplicationRole role)
{
_context.Roles.Add(role);
await _context.SaveChangesAsync();
}
public async Task UpdateAsync(ApplicationRole role)
{
_context.Roles.Update(role);
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(ApplicationRole role)
{
_context.Roles.Remove(role);
await _context.SaveChangesAsync();
}
}