using AutoMapper;
using Microsoft.Extensions.Logging;
using DigitalData.Core.Application.Interfaces.Repository;
using DigitalData.Core.Application.Interfaces;
using DigitalData.Core.Application.DTO;
namespace DigitalData.Core.Application
{
///
/// Provides generic CRUD (Create, Read, Update, Delete) operations for a specified type of entity.
///
/// The DTO type for create operations.
/// The DTO type for read operations.
/// The entity type.
/// The type of the identifier for the entity.
///
[Obsolete("Use MediatR")]
public class CRUDService : ReadService, ICRUDService
where TCRUDRepository : ICRUDRepository where TCreateDto : class where TReadDto : class where TEntity : class
{
///
/// Initializes a new instance of the CRUDService class with the specified repository, translation service, and mapper.
///
/// The CRUD repository for accessing the database.
/// The AutoMapper instance for mapping between DTOs and entity objects.
public CRUDService(TCRUDRepository repository, IMapper mapper) : base(repository: repository, mapper: mapper)
{
}
///
/// Asynchronously creates an entity based on the provided create DTO.
///
/// The DTO to create an entity from.
/// A service result indicating success or failure, including the entity DTO.
public virtual async Task> CreateAsync(TCreateDto createDto)
{
var entity = _mapper.Map(createDto);
var createdEntity = await _repository.CreateAsync(entity);
return createdEntity is null ? Result.Fail() : Result.Success(createdEntity.GetIdOrDefault());
}
///
/// Asynchronously updates an entity based on the provided update DTO.
///
/// The DTO to update an entity from.
/// A service message indicating success or failure.
public virtual async Task UpdateAsync(TUpdateDto updateDto)
{
var currentEntitiy = await _repository.ReadByIdAsync(updateDto.GetIdOrDefault());
if (currentEntitiy is null)
return Result.Fail().Notice(LogLevel.Warning, Flag.NotFound, $"{updateDto.GetIdOrDefault()} is not found in update process of {GetType()} entity.");
var entity = _mapper.Map(updateDto, currentEntitiy);
return await _repository.UpdateAsync(entity)
? Result.Success()
: Result.Fail();
}
}
}