PIbd-22_CourseWork_Hospital.../Polyclinic/HospitalDatabaseImplement/Implements/DrugStorage.cs

100 lines
3.2 KiB
C#
Raw Normal View History

2024-05-01 23:49:06 +04:00
using Microsoft.EntityFrameworkCore;
using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDatabaseImplement.Models;
using SecuritySystemDatabaseImplement;
namespace HospitalDatabaseImplement.Implements
{
public class DrugStorage : IDrugStorage
{
public List<DrugViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Drugs
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.Select(x => x.GetViewModel)
.ToList();
}
public List<DrugViewModel> GetFilteredList(DrugSearchModel model)
{
using var context = new HospitalDatabase();
if (!model.Id.HasValue || !string.IsNullOrEmpty(model.Name))
{
return new();
}
return context.Drugs
.Where(x => x.Id == model.Id || model.Name == x.Name)
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.Select(x => x.GetViewModel)
.ToList();
}
public DrugViewModel? GetElement(DrugSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new HospitalDatabase();
return context.Drugs
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?
.GetViewModel;
}
public DrugViewModel? Insert(DrugBindingModel model)
{
using var context = new HospitalDatabase();
var newDrug = Drug.Create(model);
if(newDrug == null)
{
return null;
}
context.Drugs.Add(newDrug);
context.SaveChanges();
return context.Drugs
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.FirstOrDefault(x => x.Id == newDrug.Id)?.GetViewModel;
}
public DrugViewModel? Update(DrugBindingModel model)
{
using var context = new HospitalDatabase();
var drug = context.Drugs.FirstOrDefault(x => x.Id == model.Id);
if (drug == null)
{
return null;
}
drug.Update(model);
context.SaveChanges();
return context.Drugs
.Include(x => x.Symptom)
.Include(x => x.Procedure)
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public DrugViewModel? Delete(DrugBindingModel model)
{
using var context = new HospitalDatabase();
var element = context.Drugs.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Drugs.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}