presence/data/Repository/SQLGroupRepository.cs
2024-11-26 08:09:12 +03:00

68 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();
}
return false;
}
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()
=> _dbContext.Groups.Include(g => g.Students).ToList();
public bool UpdateGroup(int id, string name)
{
Group group = _dbContext.Groups.Single(g => g.Id == id);
group.Name = name;
return _dbContext.SaveChanges() > 0;
}
}
}