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; using System.Xml.Linq; namespace HospitalDataBaseImplements.Implements { public class ProceduresStorage : IProceduresStorage { public List GetFullList() { using var context = new HospitalDatabase(); return context.Procedures.Include(x => x.Client).Include(x => x.Medicines) .ThenInclude(x => x.Medicine) .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(ProceduresSearchModel model) { if (!model.Id.HasValue && !model.ClientId.HasValue) { return new(); } using var context = new HospitalDatabase(); return context.Procedures.Include(x => x.Medicines) .ThenInclude(x => x.Medicine) .Include(x => x.Client) .Where(x => x.ClientId == model.ClientId) .Select(x => x.GetViewModel) .ToList(); } public ProceduresViewModel? GetElement(ProceduresSearchModel model) { if (string.IsNullOrEmpty(model.ProceduresName) && !model.Id.HasValue) { return null; } using var context = new HospitalDatabase(); return context.Procedures.Include(x => x.Client).Include(x => x.Medicines) .ThenInclude(x => x.Medicine) .FirstOrDefault(x => (!string.IsNullOrEmpty(model.ProceduresName) && x.ProceduresName == model.ProceduresName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public ProceduresViewModel? Insert(ProceduresBindingModel model) { var newProcedures = Procedures.Create(model); if (newProcedures == null) { return null; } using var context = new HospitalDatabase(); context.Procedures.Add(newProcedures); context.SaveChanges(); return context.Procedures.Include(x => x.Client) .Include(x => x.Medicines) .ThenInclude(x => x.Medicine).FirstOrDefault(x => x.Id == newProcedures.Id) ?.GetViewModel; } public ProceduresViewModel? Update(ProceduresBindingModel model) { using var context = new HospitalDatabase(); using var transaction = context.Database.BeginTransaction(); try { var procedure = context.Procedures.FirstOrDefault(x => x.Id == model.Id); if (procedure == null) { return null; } procedure.Update(model); context.SaveChanges(); if (model.ProcedureMedicine != null) { procedure.UpdateMedicines(context, model); } transaction.Commit(); return procedure.GetViewModel; } catch { transaction.Rollback(); throw; } } public ProceduresViewModel? Delete(ProceduresBindingModel model) { using var context = new HospitalDatabase(); var element = context.Procedures.Include(x => x.Medicines) .ThenInclude(x => x.Medicine) .Include(x => x.Client).FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Procedures.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }