ajout d'un option dans UserDbContext pour avoir plus de détaille sur les logs. Ajout de GetItems

Genericite
Victor GABORIT 1 year ago
parent a307f68fc3
commit e476fd6c82

@ -3,6 +3,7 @@ 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;
using Model;
using Model.Business; using Model.Business;
using Model.DTO; using Model.DTO;
using Model.Mappers; using Model.Mappers;
@ -35,7 +36,7 @@ namespace API.Controllers
return StatusCode(204); return StatusCode(204);
} }
_logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser); _logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser);
return Ok(_dataService.UserService.GetUsers(page, number)); return Ok(_dataService.UserService.GetItems<UserEntity>(page, number));
} }
[HttpGet("user/id/{id}")] [HttpGet("user/id/{id}")]
@ -44,7 +45,7 @@ namespace API.Controllers
try try
{ {
_logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id); _logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id);
return Ok(_dataService.UserService.GetUserById(id)); return Ok(_dataService.UserService.GetItems<UserEntity>(1, 1, UserProperty.Id.ToString(),id));
} catch (ArgumentException) } catch (ArgumentException)
{ {
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
@ -58,7 +59,7 @@ namespace API.Controllers
try try
{ {
_logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username); _logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username);
return Ok(_dataService.UserService.GetUserByUsername(username)); return Ok(_dataService.UserService.GetItems<UserEntity>(1, 1,UserProperty.Username.ToString(), username));
}catch (ArgumentException) }catch (ArgumentException)
{ {
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username); _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
@ -92,7 +93,6 @@ namespace API.Controllers
} }
_logger.LogInformation("[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}", dto.Username, dto.Password, dto.Email, dto.IsAdmin); _logger.LogInformation("[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}", dto.Username, dto.Password, dto.Email, dto.IsAdmin);
//return Created(nameof(GetUsers), _dataService.UserService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin));
return Created(nameof(GetUsers), _dataService.UserService.AddItem(dto.FromDTOToModel().FromModelToEntity())); return Created(nameof(GetUsers), _dataService.UserService.AddItem(dto.FromDTOToModel().FromModelToEntity()));
} }

@ -8,6 +8,7 @@ using Model.Business;
using ModelToEntity; using ModelToEntity;
using Services; using Services;
using System.Data.Common; using System.Data.Common;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);

@ -25,7 +25,7 @@ namespace DbContextLib
{ {
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)
{ {
optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse"); optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse").EnableSensitiveDataLogging();
} }
base.OnConfiguring(optionsBuilder); base.OnConfiguring(optionsBuilder);
} }

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public enum UserProperty
{
Id,
Username,
Password,
Email,
IsAdmin
}
}

@ -7,6 +7,8 @@ using Model.Business;
using Model; using Model;
using Model.Mappers; using Model.Mappers;
using System; using System;
using Microsoft.AspNetCore.Identity;
using System.Runtime.InteropServices.ObjectiveC;
namespace ModelToEntity namespace ModelToEntity
{ {
@ -184,6 +186,13 @@ namespace ModelToEntity
return await context.UpdateItemAsync<T, TDto>(id, newItem); return await context.UpdateItemAsync<T, TDto>(id, newItem);
} }
} }
}
public async Task<IEnumerable<T?>> GetItems<T>(int index, int count, string? orderingPropertyName = null, object? valueProperty = null) where T : class
{
using (var context = new UserDbContext())
{
return await context.GetItemsWithFilter<T>(index, count, orderingPropertyName, valueProperty);
}
}
}
} }

@ -10,6 +10,8 @@ using Model.Business;
using System.Diagnostics; using System.Diagnostics;
using DbContextLib; using DbContextLib;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace ModelToEntity namespace ModelToEntity
{ {
@ -17,7 +19,7 @@ namespace ModelToEntity
{ {
internal 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))
{ {
return Task.FromResult<T?>(default(T)); return Task.FromResult<T?>(default(T));
} }
@ -69,6 +71,34 @@ namespace ModelToEntity
return Task.FromResult<T?>(entity); return Task.FromResult<T?>(entity);
} }
internal static Task<IEnumerable<T?>> GetItemsWithFilter<T>(this DbContext context,
int index, int count, string? orderingPropertyName = null, object valueProperty = null) where T : class
{
IQueryable<T> query = context.Set<T>();
if (valueProperty != null && !string.IsNullOrEmpty(orderingPropertyName))
{
var prop = typeof(T).GetProperty(orderingPropertyName);
if (prop != null)
{
var idProp = typeof(T).GetProperty(orderingPropertyName);
if (idProp != null)
{
var parameter = Expression.Parameter(typeof(T), "entity");
var propertyAccess = Expression.Property(parameter, prop);
var constant = Expression.Constant(valueProperty);
var equality = Expression.Equal(propertyAccess, constant);
var lambda = Expression.Lambda<Func<T, bool>>(equality, parameter);
var filteredEntity = context.Set<T>().FirstOrDefault(lambda);
if (filteredEntity != null)
{
return Task.FromResult<IEnumerable<T?>>(new List<T?> { filteredEntity });
}
}
}
}
var items = query.Skip(index).Take(count).ToList();
return Task.FromResult<IEnumerable<T?>>(items);
}
} }
} }

@ -73,5 +73,11 @@ namespace Services
var item = dataServiceEF.UpdateItem<T, TDto>(id, newItem); var item = dataServiceEF.UpdateItem<T, TDto>(id, newItem);
return item; return item;
} }
public Task<IEnumerable<T?>> GetItems<T>(int index, int count, string? orderingPropertyName = null, object? valueProperty = null) where T : class
{
var items = dataServiceEF.GetItems<T>(index, count, orderingPropertyName, valueProperty);
return items;
}
} }
} }

@ -4,7 +4,7 @@
{ {
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; 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; public Task<T> UpdateItem<T, TDto>(int? id, TDto? newItem) where T : class where TDto : class;
public Task<IEnumerable<T>> GetItems<T>(int index, int count, string? orderingPropertyName = null, object? valueProperty = null) where T : class;
} }
} }

Loading…
Cancel
Save