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.
sae_2a_anglais/Project/EntityFramework/DTOToEntity/UserService.cs

85 lines
2.9 KiB

using DTO;
using Entities;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class UserService : IUserService
{
private StubbedContext _context = new StubbedContext();
public async Task<UserDTO> Add(UserDTO user)
{
UserEntity? userEntity = user.ToEntity();
if(userEntity == null)
{
throw new Exception("User Entity is null");
}
var result = await _context.Users.AddAsync(userEntity);
await _context.SaveChangesAsync();
return result.Entity.ToDTO();
}
public async Task<UserDTO> Delete(object id)
{
UserEntity? user = await _context.Users.FirstOrDefaultAsync(u => u.Id == (int)id);
if(user == null)
{
throw new Exception("User not found");
}
_context.Users.Remove(user);
await _context.SaveChangesAsync();
return user.ToDTO();
}
public async Task<PageResponse<UserDTO>> GetByGroup(int index, int count, int group)
{
var users = _context.Users.Where(u => u.GroupId == group).Skip(index).Take(count);
return new PageResponse<UserDTO>(users.Select(u => u.ToDTO()), _context.Users.Count());
}
public async Task<UserDTO> GetById(object id)
{
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == (int)id);
if(user == null)
{
throw new Exception("User not found");
}
return user.ToDTO();
}
public async Task<PageResponse<UserDTO>> GetByRole(int index, int count, string role)
{
var users = _context.Users.Where(u => u.Role.Name == role).Skip(index).Take(count);
return new PageResponse<UserDTO>(users.Select(u => u.ToDTO()), _context.Users.Count());
}
public async Task<PageResponse<UserDTO>> Gets(int index, int count)
{
var users = await _context.Users.Skip(index).Take(count).ToListAsync();
return new PageResponse<UserDTO>( users.Select(u => u.ToDTO()),_context.Users.Count());
}
public async Task<UserDTO> Update(UserDTO user)
{
var userEntity = user.ToEntity();
if(userEntity == null)
{
throw new Exception("User Entity is null");
}
if(_context.Users.FirstOrDefaultAsync(u => u.Id == userEntity.Id) == null)
{
throw new Exception("User not found");
}
var result = _context.Users.Update(userEntity);
await _context.SaveChangesAsync();
return result.Entity.ToDTO();
}
}
}