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 MedicinesStorage : IMedicinesStorage { public List GetFullList() { using var context = new HospitalDatabase(); return context.Medicines.Include(x => x.Client) .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(MedicinesSearchModel model) { if (string.IsNullOrEmpty(model.MedicinesName) && !model.ClientId.HasValue) { return new(); } using var context = new HospitalDatabase(); return context.Medicines .Include(x => x.Client) .Where(x => x.ClientId == model.ClientId) .Select(x => x.GetViewModel) .ToList(); } public MedicinesViewModel? GetElement(MedicinesSearchModel model) { if (string.IsNullOrEmpty(model.MedicinesName) && !model.Id.HasValue) { return null; } using var context = new HospitalDatabase(); return context.Medicines .FirstOrDefault(x => (!string.IsNullOrEmpty(model.MedicinesName) && x.MedicinesName == model.MedicinesName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public MedicinesViewModel? Insert(MedicinesBindingModel model) { var newMedicine = Medicines.Create(model); if (newMedicine == null) { return null; } using var context = new HospitalDatabase(); context.Medicines.Add(newMedicine); context.SaveChanges(); return newMedicine.GetViewModel; } public MedicinesViewModel? Update(MedicinesBindingModel model) { using var context = new HospitalDatabase(); var medicine = context.Medicines.FirstOrDefault(x => x.Id == model.Id); if (medicine == null) { return null; } medicine.Update(model); context.SaveChanges(); return medicine.GetViewModel; } public MedicinesViewModel? Delete(MedicinesBindingModel model) { using var context = new HospitalDatabase(); var element = context.Medicines.Include(x => x.Client).FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Medicines.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }