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 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 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> GetByGroup(int index, int count, int group) { var users = _context.Users.Where(u => u.GroupId == group).Skip(index).Take(count); return new PageResponse(users.Select(u => u.ToDTO()), _context.Users.Count()); } public async Task 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> GetByRole(int index, int count, string role) { var users = _context.Users.Where(u => u.Role.Name == role).Skip(index).Take(count); return new PageResponse(users.Select(u => u.ToDTO()), _context.Users.Count()); } public async Task> Gets(int index, int count) { var users = await _context.Users.Skip(index).Take(count).ToListAsync(); return new PageResponse( users.Select(u => u.ToDTO()),_context.Users.Count()); } public async Task 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(); } } }