ajout d'un méthode d'extension générique pour la suppression d'un item

Genericite
Victor GABORIT 1 year ago
parent 5f68add0fe
commit 7c2cc6f5ce

@ -1,4 +1,5 @@
using DbContextLib; using DbContextLib;
using Entities.SQLudeoDB;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -69,7 +70,7 @@ namespace API.Controllers
[HttpDelete] [HttpDelete]
public async Task<IActionResult> DeleteUser(int id) public async Task<IActionResult> DeleteUser(int id)
{ {
var success = await _dataService.UserService.DeleteUser(id); var success = await _dataService.UserService.DeleteItem<UserEntity>(id);
if(success) if(success)
{ {
_logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id); _logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id);

@ -166,6 +166,14 @@ namespace ModelToEntity
} }
} }
public async Task<bool> DeleteItem<T>(int id) where T : class
{
using(var context = new UserDbContext())
{
return await context.DeleteItemAsync<T>(id);
}
}
} }
} }

@ -15,7 +15,7 @@ namespace ModelToEntity
{ {
internal static class Extension internal static class Extension
{ {
public static Task<T?> CreateItemAsync<T>(this DbContext context, T? item) where T : class internal static Task<T?> CreateItemAsync<T>(this DbContext context, T? item) where T : class
{ {
if (item == null || context.Set<T>().Contains(item)) if (item == null || context.Set<T>().Contains(item))
{ {
@ -25,7 +25,25 @@ namespace ModelToEntity
context.Set<T>().Add(item); context.Set<T>().Add(item);
context.SaveChangesAsync(); context.SaveChangesAsync();
return Task.FromResult<T?>(item); ; return Task.FromResult<T?>(item);
}
internal static async Task<bool> DeleteItemAsync<T>(this DbContext context, int? id) where T : class
{
if (id == null)
{
return false;
}
var entity = await context.Set<T>().FindAsync(id);
if (entity == null)
{
return false;
}
context.Set<T>().Remove(entity);
await context.SaveChangesAsync();
return true;
} }
} }

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

@ -3,5 +3,6 @@
public interface IGenericService<T> where T : class public interface IGenericService<T> where T : class
{ {
public Task<T?> AddItem<T>(T? item) where T : class; public Task<T?> AddItem<T>(T? item) where T : class;
public Task<bool> DeleteItem<T>(int id) where T : class;
} }
} }

Loading…
Cancel
Save