using BeautySaloonContracts.BindingModels; using BeautySaloonContracts.SearchModels; using BeautySaloonContracts.StoragesContracts; using BeautySaloonContracts.ViewModels; namespace BeautySaloonDatabaseImplement.Implements { public class OrderStorage : IOrderStorage { public OrderViewModel? Delete(OrderBindingModel model) { using var context = new NewdbContext(); var element = context.Orders .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Orders.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } public OrderViewModel? GetElement(OrderSearchModel model) { using var context = new NewdbContext(); if (model.Id.HasValue) return context.Orders .FirstOrDefault(x => x.Id == model.Id)? .GetViewModel; return null; } public List GetFilteredList(OrderSearchModel model) { using var context = new NewdbContext(); if (model.ClientId.HasValue) return context.Orders .Where(x => x.ClientId == model.ClientId) .Select(x => x.GetViewModel) .ToList(); if (model.EmployeeId.HasValue) return context.Orders .Where(x => x.EmployeeId == model.EmployeeId) .Select(x => x.GetViewModel) .ToList(); if (model.Date.HasValue) return context.Orders .Where(x => x.Date == model.Date) .Select(x => x.GetViewModel) .ToList(); return new(); } public List GetFullList() { using var context = new NewdbContext(); return context.Orders .Select(x => x.GetViewModel) .ToList(); } public OrderViewModel? Insert(OrderBindingModel model) { using var context = new NewdbContext(); model.Id = context.Orders .Count() > 0 ? context.Orders.Max(x => x.Id) + 1 : 1; var newOrder = Order.Create(context, model); if (newOrder == null) { return null; } context.Orders.Add(newOrder); context.SaveChanges(); return newOrder.GetViewModel; } public OrderViewModel? Update(OrderBindingModel model) { using var context = new NewdbContext(); using var transaction = context.Database.BeginTransaction(); try { var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); if (order == null) { return null; } order.Update(model); context.SaveChanges(); order.UpdateServices(context, model); transaction.Commit(); return order.GetViewModel; } catch { transaction.Rollback(); throw; } } } }