refactor: Entfernte nicht benötigte _keyPropertyInfo und aktualisierte CreateAsync Methode
- Entfernte `_keyPropertyInfo` und die zugehörige Methode `KeyValueOf`, da sie nicht mehr benötigt wird. - Aktualisierte `CreateAsync` Methode, um direkt `createdEntity.Id` zurückzugeben.
This commit is contained in:
@@ -1,8 +1,6 @@
|
||||
using DigitalData.Core.Abstractions.Application;
|
||||
using DigitalData.Core.Abstractions.Infrastructure;
|
||||
using AutoMapper;
|
||||
using System.Reflection;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using DigitalData.Core.DTO;
|
||||
using DigitalData.Core.Abstractions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -22,7 +20,6 @@ namespace DigitalData.Core.Application
|
||||
{
|
||||
protected readonly TCRUDRepository _repository;
|
||||
protected readonly IMapper _mapper;
|
||||
protected readonly PropertyInfo? _keyPropertyInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the CRUDService class with the specified repository, translation service, and mapper.
|
||||
@@ -33,9 +30,6 @@ namespace DigitalData.Core.Application
|
||||
{
|
||||
_repository = repository;
|
||||
_mapper = mapper;
|
||||
|
||||
_keyPropertyInfo = typeof(TEntity).GetProperties()
|
||||
.FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(KeyAttribute)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -47,7 +41,7 @@ namespace DigitalData.Core.Application
|
||||
{
|
||||
var entity = _mapper.Map<TEntity>(createDto);
|
||||
var createdEntity = await _repository.CreateAsync(entity);
|
||||
return createdEntity is null ? Result.Fail<TId>() : Result.Success(KeyValueOf(createdEntity));
|
||||
return createdEntity is null ? Result.Fail<TId>() : Result.Success(createdEntity.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -120,24 +114,6 @@ namespace DigitalData.Core.Application
|
||||
return entity is not null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the ID value of an entity based on the defined [Key] attribute.
|
||||
/// </summary>
|
||||
/// <param name="entity">The entity from which to extract the ID.</param>
|
||||
/// <returns>The ID of the entity.</returns>
|
||||
protected virtual TId KeyValueOf(TEntity entity)
|
||||
{
|
||||
if (_keyPropertyInfo is null)
|
||||
throw new InvalidOperationException($"No property with [Key] attribute found on {typeof(TEntity).Name} entity.");
|
||||
|
||||
object idObj = _keyPropertyInfo?.GetValue(entity) ?? throw new InvalidOperationException($"The ID property of {typeof(TEntity).Name} entity cannot be null.");
|
||||
|
||||
if (idObj is TId id)
|
||||
return id;
|
||||
else
|
||||
throw new InvalidCastException($"The ID of {typeof(TEntity).Name} entity must be type of {typeof(TId).Name}, but it is type of {idObj.GetType().Name}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles exceptions that occur during CRUD operations, providing a structured string.
|
||||
/// </summary>
|
||||
|
||||
Reference in New Issue
Block a user