using Contracts.BindingModels; using Contracts.SearchModel; using Contracts.Storage; using Contracts.ViewModels; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataBase.Implements { public class HumanStorage : IHumanStorage { public List GetFullList() { using var context = new LogisticContext(); return context.Humans.FromSqlRaw("Select * From Human").Include(u => u.Status) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(HumanSM model) { if (!model.StatusId.HasValue) { return new(); } using var context = new LogisticContext(); return context.Humans .FromSqlRaw("Select * FROM Human WHERE status_id = {0}", model.StatusId).Include(u => u.Status) .ToList() .Select(x => x.GetViewModel) .ToList(); } public HumanVM? GetElement(HumanSM model) { if (!model.Id.HasValue && string.IsNullOrEmpty(model.Phone)) { return null; } using var context = new LogisticContext(); return context.Humans .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.Phone) && x.Phone.Equals(model.Phone))) ?.GetViewModel; } public HumanVM? Insert(HumanBM model) { using var context = new LogisticContext(); var newHuman = Human.Create(context, model); if (newHuman == null) { return null; } context.Humans.Add(newHuman); context.SaveChanges(); return newHuman.GetViewModel; } public HumanVM? Update(HumanBM model) { using var context = new LogisticContext(); using var transaction = context.Database.BeginTransaction(); try { var human = context.Humans.FirstOrDefault(rec => rec.Id == model.Id); if (human == null) { return null; } human.Update(model); context.SaveChanges(); transaction.Commit(); return human.GetViewModel; } catch { transaction.Rollback(); throw; } } public HumanVM? Delete(HumanBM model) { using var context = new LogisticContext(); var element = context.Humans .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Humans.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }