fengling-console/Repositories/RoleRepository.cs
2026-02-05 14:15:20 +08:00

87 lines
2.3 KiB
C#

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();
}
}