Rogashova_E.A._CourseWork_H.../HospitalDataBaseImplements/Implements/IllnessStorage.cs

117 lines
3.9 KiB
C#

using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDataBaseImplements.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDataBaseImplements.Implements
{
public class IllnessStorage : IIllnessStorage
{
public List<IllnessViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Illnesses
.Include(x => x.Kurses)
.ThenInclude(x => x.Kurse)
.Include(x => x.Symptomses)
.ThenInclude(x => x.Symptoms)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<IllnessViewModel> GetFilteredList(IllnessSearchModel model)
{
if (string.IsNullOrEmpty(model.IllnessName))
{
return new();
}
using var context = new HospitalDatabase();
return context.Illnesses
.Include(x => x.Kurses)
.ThenInclude(x => x.Kurse)
.Include(x => x.Symptomses)
.ThenInclude(x => x.Symptoms)
.Where(x => x.IllnessName.Contains(model.IllnessName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public IllnessViewModel? GetElement(IllnessSearchModel model)
{
if (string.IsNullOrEmpty(model.IllnessName) && !model.Id.HasValue)
{
return null;
}
using var context = new HospitalDatabase();
return context.Illnesses
.Include(x => x.Kurses)
.ThenInclude(x => x.Kurse)
.Include(x => x.Symptomses)
.ThenInclude(x => x.Symptoms)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.IllnessName) &&
x.IllnessName == model.IllnessName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public IllnessViewModel? Insert(IllnessBindingModel model)
{
using var context = new HospitalDatabase();
var newIllness = Illness.Create(context, model);
if (newIllness == null)
{
return null;
}
context.Illnesses.Add(newIllness);
context.SaveChanges();
return newIllness.GetViewModel;
}
public IllnessViewModel? Update(IllnessBindingModel model)
{
using var context = new HospitalDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var illness = context.Illnesses.FirstOrDefault(rec =>
rec.Id == model.Id);
if (illness == null)
{
return null;
}
illness.Update(model);
context.SaveChanges();
illness.UpdateDrugCourses(context, model);
illness.UpdateSymptomses(context, model);
transaction.Commit();
return illness.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public IllnessViewModel? Delete(IllnessBindingModel model)
{
using var context = new HospitalDatabase();
var element = context.Illnesses
.Include(x => x.Kurses)
.Include(x => x.Symptomses)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Illnesses.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}