hrms-api-backend/BMA.EHR.Application/Repositories/GenericRepository.cs
2023-07-28 15:04:26 +07:00

89 lines
2.6 KiB
C#

using BMA.EHR.Application.Common.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
namespace BMA.EHR.Application.Repositories
{
public class GenericRepository<S, T> : IGenericRepository<S, T> where T : class
{
#region " Field "
private readonly IApplicationDBContext _dbContext;
private readonly DbSet<T> _dbSet;
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion
#region " Constructor and Destructor "
public GenericRepository(IApplicationDBContext dbContext,
IHttpContextAccessor httpContextAccessor)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
_httpContextAccessor = httpContextAccessor;
}
#endregion
#region " Properties "
protected string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
protected string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
#endregion
#region " Methods "
public virtual async Task<IReadOnlyList<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}
public virtual async Task<T?> GetByIdAsync(S id)
{
return await _dbSet.FindAsync(id);
}
public virtual async Task<T> AddAsync(T entity)
{
//if (entity is IAuditableEntity)
//{
// (entity as IAuditableEntity).CreatedUserId = Guid.Parse(UserId);
// (entity as IAuditableEntity).CreatedUserFullName = FullName;
// (entity as IAuditableEntity).CreatedDate = DateTime.Now;
//}
await _dbSet.AddAsync(entity);
await _dbContext.SaveChangesAsync();
return entity;
}
public virtual async Task<T> UpdateAsync(T entity)
{
//if (entity is IAuditableEntity)
//{
// (entity as IAuditableEntity).ModifiedUserId = Guid.Parse(UserId);
// (entity as IAuditableEntity).ModifiedUserFullName = FullName;
// (entity as IAuditableEntity).ModifiedDate = DateTime.Now;
//}
_dbSet.Update(entity);
await _dbContext.SaveChangesAsync();
return entity;
}
public virtual async Task DeleteAsync(T entity)
{
_dbSet.Remove(entity);
await _dbContext.SaveChangesAsync();
}
#endregion
}
}