mise à jour de la structure avec ajout de service pour la partie EntityFramework et ajout de la class DbDataManager pour communiquer avec la BDD, changement des methode dans l'API qui sont maintenant en asynchrone. Changement du DbContextLib poureffectuer les migrations : ajout d'un constructeur et indication clé étrangère pour inquiryEntity

correctionLienWebServiceEF
Victor GABORIT 1 year ago
parent 9bd3088aa2
commit 5f9899276a

@ -24,6 +24,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ModelToEntity\ModelToEntity.csproj" />
<ProjectReference Include="..\Services\Services.csproj" /> <ProjectReference Include="..\Services\Services.csproj" />
</ItemGroup> </ItemGroup>

@ -24,9 +24,9 @@ namespace API.Controllers
} }
[HttpGet("users/{page}/{number}")] [HttpGet("users/{page}/{number}")]
public IActionResult GetUsers(int page, int number) public async Task<IActionResult> GetUsers(int page, int number)
{ {
var nbUser = _userDataService.GetUsers(page, number).Count(); var nbUser = (await _userDataService.GetUsers(page, number)).ToList().Count();
if(nbUser == 0) if(nbUser == 0)
{ {
_logger.LogError("[ERREUR] Aucun utilisateur trouvé."); _logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
@ -37,7 +37,7 @@ namespace API.Controllers
} }
[HttpGet("user/id/{id}")] [HttpGet("user/id/{id}")]
public IActionResult GetUserById(int id) public async Task<IActionResult> GetUserById(int id)
{ {
try try
{ {
@ -51,7 +51,7 @@ namespace API.Controllers
} }
[HttpGet("user/username/{username}")] [HttpGet("user/username/{username}")]
public IActionResult GetUserByUsername(string username) public async Task<IActionResult> GetUserByUsername(string username)
{ {
try try
{ {
@ -66,9 +66,9 @@ namespace API.Controllers
} }
[HttpDelete] [HttpDelete]
public IActionResult DeleteUser(int id) public async Task<IActionResult> DeleteUser(int id)
{ {
var success = _userDataService.DeleteUser(id); var success = await _userDataService.DeleteUser(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);
@ -82,7 +82,7 @@ namespace API.Controllers
} }
[HttpPost] [HttpPost]
public IActionResult CreateUser([FromBody]UserDTO dto) public async Task<IActionResult> CreateUser([FromBody]UserDTO dto)
{ {
if (dto.Username == null || dto.Password == null || dto.Email == null) if (dto.Username == null || dto.Password == null || dto.Email == null)
{ {
@ -94,7 +94,7 @@ namespace API.Controllers
} }
[HttpPut] [HttpPut]
public IActionResult UpdateUser(int id, [FromBody] UserDTO userDTO) public async Task<IActionResult> UpdateUser(int id, [FromBody] UserDTO userDTO)
{ {
if(id != userDTO.Id) if(id != userDTO.Id)
{ {

@ -3,7 +3,9 @@ using DbContextLib;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using ModelToEntity;
using Services; using Services;
using System.Data.Common;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -14,6 +16,7 @@ builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IDataService, UserDataService>(); builder.Services.AddScoped<IDataService, UserDataService>();
builder.Services.AddScoped<IDataServiceEF, DbDataManager>();
builder.Services.AddDbContext<DbContext, UserDbContext>(); builder.Services.AddDbContext<DbContext, UserDbContext>();
builder.Services.AddDbContext<WebAPIDbContext>(options => options.UseInMemoryDatabase("appDb")); builder.Services.AddDbContext<WebAPIDbContext>(options => options.UseInMemoryDatabase("appDb"));
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<WebAPIDbContext>(); builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<WebAPIDbContext>();

@ -3,19 +3,21 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.8.34408.163 VisualStudioVersion = 17.8.34408.163
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{65F4AE69-E1CA-4B87-BDF0-946A37351BD1}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{65F4AE69-E1CA-4B87-BDF0-946A37351BD1}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Entities", "EntityFramework\Entities.csproj", "{6D079CDA-C000-4833-98A0-D07D153EA264}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "EntityFramework\Entities.csproj", "{6D079CDA-C000-4833-98A0-D07D153EA264}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "Model\Model.csproj", "{ADCC427D-A3CD-431C-A90B-F9369C4584E8}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Model", "Model\Model.csproj", "{ADCC427D-A3CD-431C-A90B-F9369C4584E8}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestAPI", "TestAPI\TestAPI.csproj", "{17025B90-8B2A-49E9-97D3-1A84A208DF50}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestAPI", "TestAPI\TestAPI.csproj", "{17025B90-8B2A-49E9-97D3-1A84A208DF50}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestEF", "TestEF\TestEF.csproj", "{54FAD8AF-7601-4C54-8406-D81476A8D7D7}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEF", "TestEF\TestEF.csproj", "{54FAD8AF-7601-4C54-8406-D81476A8D7D7}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Services", "Services\Services.csproj", "{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Services", "Services\Services.csproj", "{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelToEntity", "ModelToEntity\ModelToEntity.csproj", "{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -51,6 +53,10 @@ Global
{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Debug|Any CPU.Build.0 = Debug|Any CPU {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.ActiveCfg = Release|Any CPU {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.Build.0 = Release|Any CPU {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.Build.0 = Release|Any CPU
{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

@ -20,6 +20,7 @@ namespace DbContextLib
public DbSet<SuccessEntity> Success { get; set; } public DbSet<SuccessEntity> Success { get; set; }
public DbSet<NotepadEntity> Notepad { get; set; } public DbSet<NotepadEntity> Notepad { get; set; }
public UserDbContext(DbContextOptions<UserDbContext> options) : base(options) { } public UserDbContext(DbContextOptions<UserDbContext> options) : base(options) { }
public UserDbContext() : base() { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ {
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)
@ -67,6 +68,7 @@ namespace DbContextLib
modelBuilder.Entity<ContentLessonEntity>().HasKey(c => c.LessonPartId); modelBuilder.Entity<ContentLessonEntity>().HasKey(c => c.LessonPartId);
modelBuilder.Entity<SuccessEntity>().HasKey(s => s.UserId); modelBuilder.Entity<SuccessEntity>().HasKey(s => s.UserId);
modelBuilder.Entity<SuccessEntity>().HasKey(s => s.InquiryId); modelBuilder.Entity<SuccessEntity>().HasKey(s => s.InquiryId);
modelBuilder.Entity<InquiryEntity>().HasKey(s => s.Id);
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
} }
} }

@ -0,0 +1,162 @@
using Entities.SQLudeoDB;
using Microsoft.EntityFrameworkCore;
using Model.DTO;
using Services;
using DbContextLib;
using Model.Business;
using Model;
using Model.Mappers;
namespace ModelToEntity
{
public class DbDataManager : IDataServiceEF
{
public async Task<User> GetUserById(int id)
{
using(var context = new UserDbContext())
{
var userEntity = context.Users.FirstOrDefault(u => u.Id == id);
if(userEntity == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
return await Task.FromResult(userEntity.FromEntityToModel());
}
}
public async Task<User> GetUserByUsername(string username)
{
using (var context = new UserDbContext())
{
var userEntity = context.Users.FirstOrDefault(u => u.Username == username);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(username));
}
return await Task.FromResult(userEntity.FromEntityToModel());
}
}
public async Task<IEnumerable<User>> GetUsers(int page, int number)
{
using (var context = new UserDbContext())
{
return await Task.FromResult(context.Users.Skip((page - 1) * number).Take(number).ToList().Select(u => u.FromEntityToModel()));
}
}
public Task<bool> DeleteUser(int id)
{
using (var context = new UserDbContext()) {
var userEntity = context.Users.FirstOrDefault(u => u.Id == id);
if (userEntity == null)
{
return Task.FromResult(false);
}
context.Users.Remove(userEntity);
context.SaveChangesAsync();
}
return Task.FromResult(true);
}
public async Task<User> UpdateUser(int id, UserDTO user)
{
using (var context = new UserDbContext())
{
var updatingUser = context.Users.FirstOrDefault(u => u.Id == id);
if (updatingUser == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
updatingUser.Username = user.Username;
updatingUser.Password = user.Password;
updatingUser.Email = user.Email;
updatingUser.IsAdmin = user.IsAdmin;
// Permet d'indiquer en Db que l'entité a été modifiée.
context.Entry(updatingUser).State = EntityState.Modified;
context.SaveChangesAsync();
return await Task.FromResult(updatingUser.FromEntityToModel());
}
}
public async Task<User> CreateUser(string username, string password, string email, bool isAdmin)
{
using (var context = new UserDbContext())
{
var newUserEntity = new UserDTO
{
Username = username,
Password = password,
Email = email,
IsAdmin = isAdmin
};
context.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity());
context.SaveChangesAsync();
return await Task.FromResult(newUserEntity.FromDTOToModel());
}
}
public IEnumerable<InquiryDTO> GetInquiries(int page, int number)
{
throw new NotImplementedException();
}
public InquiryDTO GetInquiryById(int id)
{
throw new NotImplementedException();
}
public InquiryDTO GetInquiryByTitle(string title)
{
throw new NotImplementedException();
}
public UserDTO CreateInquiry(string title, string description, bool isUser, InquiryTableEntity database, SolutionEntity inquiryTable)
{
throw new NotImplementedException();
}
public bool DeleteInquiry(int id)
{
throw new NotImplementedException();
}
public InquiryDTO UpdateInquiry(int id, InquiryDTO inquiry)
{
throw new NotImplementedException();
}
public IEnumerable<InquiryDTO> GetLessons(int page, int number)
{
throw new NotImplementedException();
}
public InquiryDTO GetLessonById(int id)
{
throw new NotImplementedException();
}
public InquiryDTO GetLessonByTitle(string title)
{
throw new NotImplementedException();
}
public bool DeleteLesson(int id)
{
throw new NotImplementedException();
}
public InquiryDTO UpdateLesson(int id, LessonDTO lesson)
{
throw new NotImplementedException();
}
public UserDTO CreateLesson(string title, string lastPublisher, DateOnly lastEdit)
{
throw new NotImplementedException();
}
}
}

@ -0,0 +1,16 @@
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using Entities.SQLudeoDB;
using Model.Business;
namespace ModelToEntity
{
static class Extension
{
}
}

@ -0,0 +1,33 @@
using Entities.SQLudeoDB;
using Model.Business;
using Model.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public interface IDataServiceEF
{
public Task<IEnumerable<User>> GetUsers(int page, int number);
public Task<User> GetUserById(int id);
public Task<User> GetUserByUsername(string username);
public Task<bool> DeleteUser(int id);
public Task<User> UpdateUser(int id, UserDTO user);
public Task<User> CreateUser(string username, string password, string email, bool isAdmin);
public IEnumerable<InquiryDTO> GetInquiries(int page, int number);
public InquiryDTO GetInquiryById(int id);
public InquiryDTO GetInquiryByTitle(string title);
public bool DeleteInquiry(int id);
public InquiryDTO UpdateInquiry(int id, InquiryDTO inquiry);
public UserDTO CreateInquiry(string title, string description, bool isUser, InquiryTableEntity database, SolutionEntity inquiryTable);
public IEnumerable<InquiryDTO> GetLessons(int page, int number);
public InquiryDTO GetLessonById(int id);
public InquiryDTO GetLessonByTitle(string title);
public bool DeleteLesson(int id);
public InquiryDTO UpdateLesson(int id, LessonDTO lesson);
public UserDTO CreateLesson(string title, string lastPublisher, DateOnly lastEdit);
}
}

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DbContextLib\DbContextLib.csproj" />
<ProjectReference Include="..\EntityFramework\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

@ -6,12 +6,12 @@ namespace Services
{ {
public interface IDataService public interface IDataService
{ {
public IEnumerable<UserDTO> GetUsers(int page, int number); public Task<IEnumerable<UserDTO>> GetUsers(int page, int number);
public UserDTO GetUserById(int id); public Task<UserDTO> GetUserById(int id);
public UserDTO GetUserByUsername(string username); public Task<UserDTO> GetUserByUsername(string username);
public bool DeleteUser(int id); public Task<bool> DeleteUser(int id);
public UserDTO UpdateUser(int id, UserDTO user); public Task<UserDTO> UpdateUser(int id, UserDTO user);
public UserDTO CreateUser(string username, string password, string email, bool isAdmin); public Task<UserDTO> CreateUser(string username, string password, string email, bool isAdmin);
public IEnumerable<InquiryDTO> GetInquiries(int page, int number); public IEnumerable<InquiryDTO> GetInquiries(int page, int number);
public InquiryDTO GetInquiryById(int id); public InquiryDTO GetInquiryById(int id);
public InquiryDTO GetInquiryByTitle(string title); public InquiryDTO GetInquiryByTitle(string title);

@ -22,6 +22,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DbContextLib\DbContextLib.csproj" /> <ProjectReference Include="..\DbContextLib\DbContextLib.csproj" />
<ProjectReference Include="..\EntityFramework\Entities.csproj" /> <ProjectReference Include="..\EntityFramework\Entities.csproj" />
<ProjectReference Include="..\ModelToEntity\ModelToEntity.csproj" />
<ProjectReference Include="..\Model\Model.csproj" /> <ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup> </ItemGroup>

@ -9,85 +9,52 @@ using Model.Mappers;
using Model.Business; using Model.Business;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Entities.SQLudeoDB; using Entities.SQLudeoDB;
using ModelToEntity;
namespace Services namespace Services
{ {
public class UserDataService : IDataService public class UserDataService : IDataService
{ {
private UserDbContext DbContext { get; set; } private UserDbContext DbContext { get; set; }
public UserDataService(UserDbContext context) private readonly IDataServiceEF dataServiceEF;
public UserDataService(IDataServiceEF dataServiceEF)
{ {
DbContext = context; this.dataServiceEF = dataServiceEF;
context.Database.EnsureCreated();
} }
public UserDTO GetUserById(int id) public async Task<UserDTO> GetUserById(int id)
{ {
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id); var user = await dataServiceEF.GetUserById(id);
if (userEntity == null) return user.FromModelToDTO();
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
return userEntity.FromEntityToModel().FromModelToDTO();
} }
public UserDTO GetUserByUsername(string username) public async Task<UserDTO> GetUserByUsername(string username)
{ {
var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username); var user = await dataServiceEF.GetUserByUsername(username);
if (userEntity == null) return user.FromModelToDTO();
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(username));
}
return userEntity.FromEntityToModel().FromModelToDTO();
} }
public IEnumerable<UserDTO> GetUsers(int page, int number) public async Task<IEnumerable<UserDTO>> GetUsers(int page, int number)
{ {
return DbContext.Users.Skip((page - 1) * number).Take(number).ToList().Select(u => u.FromEntityToModel().FromModelToDTO()); var users = await dataServiceEF.GetUsers(page, number);
return users.Select(u => u.FromModelToDTO());
} }
public bool DeleteUser(int id) public async Task<bool> DeleteUser(int id)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id);
if (userEntity == null)
{ {
return false; var respons = await dataServiceEF.DeleteUser(id);
} return respons;
DbContext.Users.Remove(userEntity);
DbContext.SaveChangesAsync();
return true;
} }
public UserDTO UpdateUser(int id, UserDTO user) public async Task<UserDTO> UpdateUser(int id, UserDTO user)
{
var updatingUser = DbContext.Users.FirstOrDefault(u => u.Id == id);
if (updatingUser == null)
{ {
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id)); var updatingUser = await dataServiceEF.UpdateUser(id, user);
} return updatingUser.FromModelToDTO();
updatingUser.Username = user.Username;
updatingUser.Password = user.Password;
updatingUser.Email = user.Email;
updatingUser.IsAdmin = user.IsAdmin;
// Permet d'indiquer en Db que l'entité a été modifiée.
DbContext.Entry(updatingUser).State = EntityState.Modified;
DbContext.SaveChangesAsync();
return updatingUser.FromEntityToModel().FromModelToDTO();
} }
public async Task<UserDTO> CreateUser(string username, string password, string email, bool isAdmin)
public UserDTO CreateUser(string username, string password, string email, bool isAdmin)
{
var newUserEntity = new UserDTO
{ {
Username = username, var newUserEntity = await dataServiceEF.CreateUser(username, password, email, isAdmin);
Password = password, return newUserEntity.FromModelToDTO();
Email = email,
IsAdmin = isAdmin
};
DbContext.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity());
DbContext.SaveChangesAsync();
return newUserEntity;
} }
public IEnumerable<InquiryDTO> GetInquiries(int page, int number) public IEnumerable<InquiryDTO> GetInquiries(int page, int number)

Loading…
Cancel
Save