using ComputerShopContracts.BindingModels; using ComputerShopContracts.SearchModels; using ComputerShopContracts.StorageContracts; using ComputerShopContracts.ViewModels; using ComputerShopDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; namespace ComputerShopDatabaseImplement.Implements { public class AssemblyStorage : IAssemblyStorage { public List GetFullList() { using var Context = new ComputerShopDatabase(); return Context.Assemblies .Include(x => x.Components) .ThenInclude(x => x.Assembly) .Select(x => x.ViewModel) .ToList(); } public List GetFilteredList(AssemblySearchModel Model) { using var Context = new ComputerShopDatabase(); // сборки по комплектующим return Context.Assemblies .Include(x => x.Components) .ThenInclude(x => x.Assembly) .Select(x => x.ViewModel) .ToList(); } public AssemblyViewModel? GetElement(AssemblySearchModel Model) { using var Context = new ComputerShopDatabase(); return Context.Assemblies .Include(x => x.Components) .ThenInclude(x => x.Assembly) .FirstOrDefault(x => x.Id == Model.Id)? .ViewModel; } public AssemblyViewModel? Insert(AssemblyBindingModel Model) { using var Context = new ComputerShopDatabase(); var NewAssembly = Assembly.Create(Context, Model); Context.Assemblies.Add(NewAssembly); Context.SaveChanges(); return NewAssembly.ViewModel; } public AssemblyViewModel? Update(AssemblyBindingModel Model) { using var Context = new ComputerShopDatabase(); using var Transaction = Context.Database.BeginTransaction(); try { var ExistingAssembly = Context.Assemblies.FirstOrDefault(x => x.Id == Model.Id); if (ExistingAssembly == null) { return null; } ExistingAssembly.Update(Model); Context.SaveChanges(); ExistingAssembly.UpdateComponents(Context, Model); Transaction.Commit(); return ExistingAssembly.ViewModel; } catch { Transaction.Rollback(); throw; } } public AssemblyViewModel? Delete(AssemblyBindingModel Model) { using var Context = new ComputerShopDatabase(); var ExistingAssembly = Context.Assemblies.Include(x => x.Components).FirstOrDefault(x => x.Id == Model.Id); if (ExistingAssembly == null) { return null; } Context.Assemblies.Remove(ExistingAssembly); Context.SaveChanges(); return ExistingAssembly.ViewModel; } } }