PIbd-21_CourseWork_Polyclin.../Polyclinic/PolyclinicDatabaseImplement/Implements/CourseStorage.cs

89 lines
2.8 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore;
using PolyclinicContracts.BindingModels;
using PolyclinicContracts.SearchModels;
using PolyclinicContracts.StoragesContracts;
using PolyclinicContracts.ViewModels;
using PolyclinicDatabaseImplement.Models;
using SecuritySystemDatabaseImplement;
namespace PolyclinicDatabaseImplement.Implements
{
public class CourseStorage : ICourseStorage
{
public CourseViewModel? Delete(CourseBindingModel model)
{
using var context = new PolyclinicDatabase();
var element = context.Courses.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Courses.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public CourseViewModel? GetElement(CourseSearchModel model)
{
return GetFilteredList(model).FirstOrDefault();
}
public List<CourseViewModel> GetFilteredList(CourseSearchModel model)
{
var elements = GetFullList();
if (model.Id != null)
{
elements = elements.Where(x => x.Id == model.Id).ToList();
}
return elements;
}
public List<CourseViewModel> GetFullList()
{
using var context = new PolyclinicDatabase();
return context.Courses
.Include(x => x.Diagnoses)
.ThenInclude(x => x.Diagnose)
.Select(x => x.GetViewModel)
.ToList();
}
public CourseViewModel? Insert(CourseBindingModel model)
{
using var context = new PolyclinicDatabase();
var element = Course.Create(context, model);
if (element == null)
{
return null;
}
context.Courses.Add(element);
context.SaveChanges();
return element.GetViewModel;
}
public CourseViewModel? Update(CourseBindingModel model)
{
using var context = new PolyclinicDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var element = context.Courses.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
element.UpdateDiagnoses(context, model);
transaction.Commit();
return element.GetViewModel;
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}
}
}