ajout d'UpdateItem générique, la mise à jour se fait en base de donnée mais PUT renvoie un code de retour 500 car elle ne renvoie pas un object sérializable : à corriger

Genericite
Victor GABORIT 1 year ago
parent 7c2cc6f5ce
commit de66affddc

@ -112,7 +112,7 @@ namespace API.Controllers
if(userDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée", id);
return Ok(_dataService.UserService.UpdateUser(id, userDTO));
return Ok(_dataService.UserService.UpdateItem<UserEntity, UserDTO>(id, userDTO));
}
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();

@ -6,6 +6,7 @@ using DbContextLib;
using Model.Business;
using Model;
using Model.Mappers;
using System;
namespace ModelToEntity
{
@ -174,6 +175,15 @@ namespace ModelToEntity
return await context.DeleteItemAsync<T>(id);
}
}
public async Task<T?> UpdateItem<T, TDto>(int? id, TDto? newItem)
where T : class
where TDto : class
{
using(var context = new UserDbContext())
{
return await context.UpdateItemAsync<T, TDto>(id, newItem);
}
}
}
}

@ -45,6 +45,30 @@ namespace ModelToEntity
return true;
}
internal static Task<T?> UpdateItemAsync<T, TDto>(this DbContext context, int? id, TDto dto)
where T : class
where TDto : class
{
var entity = context.Set<T>().FindAsync(id);
if (entity == null)
{
throw new ArgumentException("Impossible de trouver l'entité", nameof(id));
}
var propertiesToUpdate = typeof(TDto).GetProperties()
.Where(p => p.CanRead && p.CanWrite);
foreach (var property in propertiesToUpdate)
{
var value = property.GetValue(dto);
typeof(T).GetProperty(property.Name)?.SetValue(entity, value);
}
context.Entry(entity).State = EntityState.Modified;
context.SaveChangesAsync();
return Task.FromResult<T?>(entity as T);
}
}
}

@ -67,5 +67,11 @@ namespace Services
var succes = dataServiceEF.DeleteItem<T>(id);
return succes;
}
public Task<T> UpdateItem<T, TDto>(int? id, TDto? newItem) where T : class where TDto : class
{
var item = dataServiceEF.UpdateItem<T, TDto>(id, newItem);
return item;
}
}
}

@ -4,5 +4,7 @@
{
public Task<T?> AddItem<T>(T? item) where T : class;
public Task<bool> DeleteItem<T>(int id) where T : class;
public Task<T> UpdateItem<T, TDto>(int? id, TDto? newItem) where T : class where TDto : class;
}
}

Loading…
Cancel
Save