You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.5 KiB
90 lines
2.5 KiB
using DbContextLib;
|
|
using Entities;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Shared;
|
|
|
|
namespace DbDataManager.Service;
|
|
|
|
public class UserDataService : IUserService<UserEntity>
|
|
{
|
|
private UserDbContext DbContext { get; set; }
|
|
|
|
public UserDataService(UserDbContext context)
|
|
{
|
|
DbContext = context;
|
|
context.Database.EnsureCreated();
|
|
}
|
|
|
|
public UserEntity GetUserById(int id)
|
|
{
|
|
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id);
|
|
if (userEntity == null)
|
|
{
|
|
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
|
|
}
|
|
|
|
return userEntity;
|
|
}
|
|
|
|
public UserEntity GetUserByUsername(string username)
|
|
{
|
|
var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username);
|
|
if (userEntity == null)
|
|
{
|
|
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(username));
|
|
}
|
|
|
|
return userEntity;
|
|
}
|
|
|
|
public IEnumerable<UserEntity> GetUsers(int page, int number)
|
|
{
|
|
return DbContext.Users.Skip((page - 1) * number).Take(number).ToList()
|
|
.Select(u => u);
|
|
}
|
|
|
|
public bool DeleteUser(int id)
|
|
{
|
|
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id);
|
|
if (userEntity == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
DbContext.Users.Remove(userEntity);
|
|
DbContext.SaveChangesAsync();
|
|
return true;
|
|
}
|
|
|
|
public UserEntity UpdateUser(int id, UserEntity user)
|
|
{
|
|
var updatingUser = DbContext.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.
|
|
DbContext.Entry(updatingUser).State = EntityState.Modified;
|
|
DbContext.SaveChangesAsync();
|
|
return updatingUser;
|
|
}
|
|
|
|
public UserEntity CreateUser(string username, string password, string email, bool isAdmin)
|
|
{
|
|
var newUserEntity = new UserEntity()
|
|
{
|
|
Username = username,
|
|
Password = password,
|
|
Email = email,
|
|
IsAdmin = isAdmin
|
|
};
|
|
DbContext.Users.Add(newUserEntity);
|
|
DbContext.SaveChangesAsync();
|
|
return newUserEntity;
|
|
}
|
|
} |