68 lines
2.0 KiB
C#
68 lines
2.0 KiB
C#
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;
|
||
}
|
||
}
|
||
}
|