PIbd-22_Shabunov_O.A._SushiBar/SushiBarDatabaseImplement/Storages/DishStorage.cs
2024-05-24 01:56:34 +04:00

103 lines
2.9 KiB
C#

using Microsoft.EntityFrameworkCore;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement.Storages
{
public class DishStorage
{
public List<DishViewModel> GetFullList()
{
using var Context = new SushiBarDatabase();
return Context.Dishes
.Include(x => x.Ingredients)
.ThenInclude(x => x.Ingredient)
.Select(x => x.ViewModel)
.ToList();
}
public List<DishViewModel> GetFilteredList(DishSearchModel Model)
{
if (string.IsNullOrEmpty(Model.DishName))
return new();
using var Context = new SushiBarDatabase();
return Context.Dishes
.Include(x => x.Ingredients)
.ThenInclude(x => x.Ingredient)
.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.Ingredients)
.ThenInclude(x => x.Ingredient)
.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
.FirstOrDefault(rec => rec.Id == Model.Id);
if (Dish == null)
return null;
Context.Dishes.Remove(Dish);
Context.SaveChanges();
return Dish.ViewModel;
}
}
}