pr1/presence/data/Repository/GroupRepositoryImpl.cs

114 lines
3.7 KiB
C#
Raw Normal View History

2024-12-19 17:36:57 +00:00
using Demo.Data.RemoteData.RemoteDataBase.DAO;
using Demo.Data.RemoteData.RemoteDataBase;
using Demo.Data.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace data.Repository
{
public class SQLGroupRepositoryImpl : IGroupRepository
{
private readonly RemoteDatabaseContext _remoteDatabaseContext;
public SQLGroupRepositoryImpl(RemoteDatabaseContext remoteDatabaseContext)
{
_remoteDatabaseContext = remoteDatabaseContext;
}
public bool AddGroup(GroupDao group)
{
var groupDao = new GroupDao
{
Name = group.Name
};
_remoteDatabaseContext.Groups.Add(groupDao);
_remoteDatabaseContext.SaveChanges();
return true;
}
public List<GroupDao> GetAllGroup()
{
return _remoteDatabaseContext.Groups
.Include(g => g.Users)
.Select(g => new GroupDao
{
Name = g.Name,
Id = g.Id,
Users = g.Users.Select(u => new UserDao
{
FIO = u.FIO,
UserId = u.UserId,
GroupId = u.GroupId
}).ToList()
}).ToList();
}
public GroupDao GetGroupById(int groupID)
{
var groupLocal = _remoteDatabaseContext.Groups
.Where(g => g.Id == groupID).FirstOrDefault();
if (groupLocal == null) return null;
return groupLocal;
}
public bool RemoveGroupById(int groupID)
{
var groupLocal = _remoteDatabaseContext.Groups
.Where(x => x.Id == groupID).FirstOrDefault();
if (groupLocal == null) return false;
var userLocal = _remoteDatabaseContext.Users.Where(x => x.GroupId == groupID).ToList();
if (userLocal == null) return false;
foreach (var user in userLocal)
{
_remoteDatabaseContext.Users.Remove(user);
}
_remoteDatabaseContext.Groups.Remove(groupLocal);
_remoteDatabaseContext.SaveChanges();
return true;
}
public bool UpdateGroupById(int groupID, string name)
{
var groupLocal = _remoteDatabaseContext.Groups
.Include(g => g.Users)
.Where(x => x.Id == groupID).FirstOrDefault();
if (groupLocal == null) return false;
groupLocal.Name = name;
groupLocal.Users = _remoteDatabaseContext.Users
.Where(x => x.GroupId == groupLocal.Id)
.Select(user => new UserDao
{
UserId = user.UserId,
FIO = user.FIO,
GroupId = user.GroupId
}).ToList();
_remoteDatabaseContext.SaveChanges();
return true;
}
public bool AddStudents(GroupDao group, List<UserDao> students)
{
_remoteDatabaseContext.Groups.Add(group);
_remoteDatabaseContext.SaveChanges();
foreach (UserDao student in students)
{
_remoteDatabaseContext.Users.Add(student);
}
_remoteDatabaseContext.SaveChanges();
return true;
}
public async Task<IEnumerable<GroupDao>> getAllGroupAsync()
{
return await _remoteDatabaseContext.Groups.Include(group => group.Users).ToListAsync();
}
}
}