PIbd-32_Artamonova_T.V._COP_2/UniversityDatabaseImplement/Implements/StudentStorage.cs

120 lines
3.7 KiB
C#

using UniversityContracts.BindingModels;
using UniversityContracts.StoragesContracts;
using UniversityContracts.ViewModels;
using UniversityDatabaseImplement;
using UniversityDatabaseImplement.Models;
namespace UniversityUniversityDatabaseImplement.Implements
{
public class StudentStorage : IStudentStorage
{
public void Delete(StudentBindingModel model)
{
var context = new UniversityDatabase();
var student = context.Students.FirstOrDefault(rec => rec.Id == model.Id);
if (student != null)
{
context.Students.Remove(student);
context.SaveChanges();
}
else
{
throw new Exception("Студент не найден");
}
}
public StudentViewModel GetElement(StudentBindingModel model)
{
if (model == null)
{
return null;
}
using var context = new UniversityDatabase();
var student = context.Students
.ToList()
.FirstOrDefault(rec => rec.Id == model.Id);
return student != null ? CreateModel(student) : null;
}
public List<StudentViewModel> GetFilteredList(StudentBindingModel model)
{
var context = new UniversityDatabase();
return context.Students
.Where(student => student.FIO.Contains(model.FIO))
.ToList()
.Select(CreateModel)
.ToList();
}
public List<StudentViewModel> GetFullList()
{
using var context = new UniversityDatabase();
return context.Students
.ToList()
.Select(CreateModel)
.ToList();
}
public void Insert(StudentBindingModel model)
{
var context = new UniversityDatabase();
var transaction = context.Database.BeginTransaction();
try
{
context.Students.Add(CreateModel(model, new Student()));
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public void Update(StudentBindingModel model)
{
var context = new UniversityDatabase();
var transaction = context.Database.BeginTransaction();
try
{
var student = context.Students.FirstOrDefault(rec => rec.Id == model.Id);
if (student == null)
{
throw new Exception("Студент не найден");
}
CreateModel(model, student);
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
private static Student CreateModel(StudentBindingModel model, Student student)
{
student.FIO = model.FIO;
student.PhotoFilePath = model.PhotoFilePath;
student.Email = model.Email;
student.DirectionName = model.DirectionName;
return student;
}
private StudentViewModel CreateModel(Student student)
{
return new StudentViewModel
{
Id = student.Id,
FIO = student.FIO,
PhotoFilePath = student.PhotoFilePath,
Email = student.Email,
DirectionName = student.DirectionName,
};
}
}
}