presence/data/Repository/SQLGroupRepository.cs

120 lines
3.7 KiB
C#
Raw Permalink Normal View History

2024-11-26 05:09:12 +00:00
using data.DAO;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace data.Repository
{
public class SQLGroupRepository : IGroupRepository
{
private readonly DatabaseContext _dbContext;
public SQLGroupRepository(DatabaseContext dbContext)
{
_dbContext = dbContext;
}
public bool AddGroupWithStudents(Group group, IEnumerable<Student> students)
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
_dbContext.Groups.Add(group);
_dbContext.SaveChanges();
foreach (var item in students)
{
item.Group = group;
_dbContext.Students.Add(item);
}
_dbContext.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
Debug.WriteLine("Во время добавления группы со студентами произошла ошибка: ", ex.Message);
transaction.Rollback();
2024-12-12 07:20:21 +00:00
}
return false;
}
public bool AddStudentsToGroup(int id, IEnumerable<Student> students)
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
Group group = _dbContext.Groups.Find(id);
foreach (var student in students)
{
student.Group = group;
student.GroupId = id;
_dbContext.Students.Add(student);
}
_dbContext.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
Console.WriteLine("Во время добавления студентов в группу произошла ошибка: ", ex.Message);
transaction.Rollback();
2024-11-26 05:09:12 +00:00
}
2024-12-12 07:20:21 +00:00
return false;
2024-11-26 05:09:12 +00:00
}
public bool CreateGroup(Group group)
{
_dbContext.Groups.Add(group);
return _dbContext.SaveChanges() > 0;
}
public bool DeleteGroup(int id)
{
Group group = _dbContext.Groups.Single(g => g.Id == id);
_dbContext.Groups.Remove(group);
return _dbContext.SaveChanges() > 0;
}
public IEnumerable<Group> GetAllGroups()
2024-12-04 12:21:15 +00:00
=> _dbContext.Groups
.Include(g => g.Students)
.Include(g => g.StudentGroupsSubjects)
.ThenInclude(sgs => sgs.Subject)
.ToList();
2024-11-26 05:09:12 +00:00
public bool UpdateGroup(int id, string name)
{
Group group = _dbContext.Groups.Single(g => g.Id == id);
group.Name = name;
return _dbContext.SaveChanges() > 0;
}
2024-12-12 07:20:21 +00:00
public bool RemoveStudentsFromGroup(int id)
{
var students = _dbContext.Students.Where(s => s.GroupId == id).ToList();
_dbContext.Students.RemoveRange(students);
return _dbContext.SaveChanges() > 0;
}
public bool RemoveStudentsFromGroupByIds(int id, IEnumerable<int> studentIds)
{
var studentsToRemove = _dbContext.Students
.Where(s => s.GroupId == id && studentIds.Contains(s.Id))
.ToList();
if (studentsToRemove.Any())
{
_dbContext.Students.RemoveRange(studentsToRemove);
return _dbContext.SaveChanges() > 0;
}
return false;
}
2024-11-26 05:09:12 +00:00
}
}