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

100 lines
3.4 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 MedicamentStorage : IMedicamentStorage
{
public List<MedicamentViewModel> GetFullList()
{
using var context = new PolyclinicDatabase();
return context.Medicaments
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.Select(x => x.GetViewModel)
.ToList();
}
public List<MedicamentViewModel> GetFilteredList(MedicamentSearchModel model)
{
using var context = new PolyclinicDatabase();
if (!model.Id.HasValue || !string.IsNullOrEmpty(model.Name))
{
return new();
}
return context.Medicaments
.Where(x => x.Id == model.Id || model.Name == x.Name)
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.Select(x => x.GetViewModel)
.ToList();
}
public MedicamentViewModel? GetElement(MedicamentSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new PolyclinicDatabase();
return context.Medicaments
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?
.GetViewModel;
}
public MedicamentViewModel? Insert(MedicamentBindingModel model)
{
using var context = new PolyclinicDatabase();
var newMedicament = Medicament.Create(model);
if(newMedicament == null)
{
return null;
}
context.Medicaments.Add(newMedicament);
context.SaveChanges();
return context.Medicaments
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.FirstOrDefault(x => x.Id == newMedicament.Id)?.GetViewModel;
}
public MedicamentViewModel? Update(MedicamentBindingModel model)
{
using var context = new PolyclinicDatabase();
var medicament = context.Medicaments.FirstOrDefault(x => x.Id == model.Id);
if (medicament == null)
{
return null;
}
medicament.Update(model);
context.SaveChanges();
return context.Medicaments
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public MedicamentViewModel? Delete(MedicamentBindingModel model)
{
using var context = new PolyclinicDatabase();
var element = context.Medicaments.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Medicaments.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}