using Contracts.BindingModels; using Contracts.SearchModels; using Contracts.StoragesContracts; using Contracts.ViewModels; using DatabaseImplement.Models; using Microsoft.EntityFrameworkCore; namespace DatabaseImplement.Implements { public class ProductionStorage : IProductionStorage { public ProductionViewModel? Delete(ProductionBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newProduction = context.Productions.FirstOrDefault(x => x.Id == model.Id); if (newProduction == null) return null; newProduction.UpdateDetails(context, model); context.Productions.Remove(newProduction); context.SaveChanges(); return newProduction.GetViewModel; } public ProductionViewModel? GetElement(ProductionSearchModel model) { using var context = new FactoryGoWorkDatabase(); return context.Productions.Include(x => x.Details).ThenInclude(x => x.Detail).FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(ProductionSearchModel model) { if (!model.UserId.HasValue && !model.DetailId.HasValue) { return new(); } using var context = new FactoryGoWorkDatabase(); if (model.DetailId.HasValue) return context.Productions.Include(x => x.Details).ThenInclude(x => x.Detail).Where(x => x.UserId == model.UserId).Where(x => x.Details.FirstOrDefault(y => y.DetailId == model.DetailId) != null).Include(x => x.User).Select(x => x.GetViewModel).ToList(); else return context.Productions.Include(x => x.Details).ThenInclude(x => x.Detail).Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList(); } public List GetFullList() { using var context = new FactoryGoWorkDatabase(); return context.Productions.Include(x => x.Details).ThenInclude(x => x.Detail).Select(x => x.GetViewModel).ToList(); } public ProductionViewModel? Insert(ProductionBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newProduction = Production.Create(context, model); if (newProduction == null) return null; context.Productions.Add(newProduction); context.SaveChanges(); return newProduction.GetViewModel; } public ProductionViewModel? Update(ProductionBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newProduction = context.Productions.FirstOrDefault(x => x.Id == model.Id); if (newProduction == null) return null; newProduction.Update(model); newProduction.UpdateDetails(context, model); context.SaveChanges(); return newProduction.GetViewModel; } } }