presence_api/data/Repository/SQLUserRepositoryImpl.cs
2024-11-11 14:35:05 +03:00

62 lines
2.0 KiB
C#

using data.Exceptions;
using data.RemoteData.RemoteDataBase;
using data.RemoteData.RemoteDataBase.DAO;
using data.domain.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace data.Repository
{
public class SQLUserRepositoryImpl : IUserRepository
{
private readonly RemoteDatabaseContext _remoteDatabaseContext;
public SQLUserRepositoryImpl(RemoteDatabaseContext remoteDatabaseContext)
{
_remoteDatabaseContext = remoteDatabaseContext;
}
public bool RemoveUserById(int userId)
{
var user = _remoteDatabaseContext.Users.FirstOrDefault(u => u.UserId == userId);
if (user == null) throw new UserNotFoundException(userId);
_remoteDatabaseContext.Users.Remove(user);
_remoteDatabaseContext.SaveChanges();
return true;
}
public UserDao UpdateUser(int userId, string newFio, int groupId)
{
var existingUser = _remoteDatabaseContext.Users.FirstOrDefault(u => u.UserId == userId);
if (existingUser == null) throw new UserNotFoundException(userId);
// Обновляем поля существующего пользователя
existingUser.FIO = newFio;
existingUser.GroupId = groupId;
_remoteDatabaseContext.SaveChanges();
return existingUser;
}
public List<UserDao> GetAllUsers()
{
// Возвращаем пользователей, отсортированных по UserId
return _remoteDatabaseContext.Users.OrderBy(u => u.UserId).ToList();
}
public List<UserDao> GetUserNames()
{
var users = GetAllUsers();
List<UserDao> names = new List<UserDao>();
foreach (var user in users)
{
names.Add(new UserDao { UserId = user.UserId, FIO = user.FIO });
}
return names;
}
}
}