using Microsoft.EntityFrameworkCore; using SushiBarContracts.BindingModels; using SushiBarContracts.SearchModels; using SushiBarContracts.ViewModels; using SushiBarDatabaseImplement.Models; namespace SushiBarDatabaseImplement.Storages { public class DishStorage { public List GetFullList() { using var Context = new SushiBarDatabase(); return Context.Dishes .Include(x => x.DishIngredients) .Select(x => x.ViewModel) .ToList(); } public List GetFilteredList(DishSearchModel Model) { if (string.IsNullOrEmpty(Model.DishName)) return new(); using var Context = new SushiBarDatabase(); return Context.Dishes .Include(x => x.DishIngredients) .Where(x => x.DishName.Contains(Model.DishName)) .Select(x => x.ViewModel) .ToList(); } public DishViewModel? GetElement(DishSearchModel Model) { if (!Model.Id.HasValue) return null; using var Context = new SushiBarDatabase(); return Context.Dishes .Include(x => x.DishIngredients) .FirstOrDefault(x => x.Id == Model.Id)?.ViewModel; } public DishViewModel? Insert(DishBindingModel Model) { using var Context = new SushiBarDatabase(); var NewDish = Dish.Create(Context, Model); if (NewDish == null) return null; Context.Dishes.Add(NewDish); Context.SaveChanges(); return NewDish.ViewModel; } public DishViewModel? Update(DishBindingModel Model) { using var Context = new SushiBarDatabase(); using var Transaction = Context.Database.BeginTransaction(); try { var Dish = Context.Dishes.FirstOrDefault(x => x.Id == Model.Id); if (Dish == null) return null; Dish.Update(Model); Context.SaveChanges(); Dish.UpdateIngredients(Context, Model); Transaction.Commit(); return Dish.ViewModel; } catch { Transaction.Rollback(); throw; } } public DishViewModel? Delete(DishBindingModel Model) { using var Context = new SushiBarDatabase(); var Dish = Context.Dishes .Include(x => x.DishIngredients) .FirstOrDefault(rec => rec.Id == Model.Id); if (Dish == null) return null; Context.Dishes.Remove(Dish); Context.SaveChanges(); return Dish.ViewModel; } } }