PIbd-22_Shabunov_O.A._SushiBar/SushiBarDatabaseImplement/Storages/IngredientStorage.cs
2024-05-16 17:13:55 +04:00

81 lines
2.4 KiB
C#

using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement.Storages
{
public class IngredientStorage
{
public List<IngredientViewModel> GetFullList()
{
using var Context = new SushiBarDatabase();
return Context.Ingredients.Select(x => x.ViewModel).ToList();
}
public List<IngredientViewModel> GetFilteredList(IngredientSearchModel Model)
{
if (string.IsNullOrEmpty(Model.IngredientName))
return new();
using var Context = new SushiBarDatabase();
return Context.Ingredients
.Where(x => x.IngredientName.Contains(Model.IngredientName))
.Select(x => x.ViewModel)
.ToList();
}
public IngredientViewModel? GetElement(IngredientSearchModel Model)
{
if (!Model.Id.HasValue)
return null;
using var Context = new SushiBarDatabase();
return Context.Ingredients
.FirstOrDefault(x => x.Id == Model.Id)?.ViewModel;
}
public IngredientViewModel? Insert(IngredientBindingModel Model)
{
var NewIngredient = Ingredient.Create(Model);
if (NewIngredient == null)
return null;
using var Context = new SushiBarDatabase();
Context.Ingredients.Add(NewIngredient);
Context.SaveChanges();
return NewIngredient.ViewModel;
}
public IngredientViewModel? Update(IngredientBindingModel Model)
{
using var Context = new SushiBarDatabase();
var Ingredient = Context.Ingredients.FirstOrDefault(x => x.Id == Model.Id);
if (Ingredient == null)
return null;
Ingredient.Update(Model);
Context.SaveChanges();
return Ingredient.ViewModel;
}
public IngredientViewModel? Delete(IngredientBindingModel Model)
{
using var Context = new SushiBarDatabase();
var Ingredient = Context.Ingredients.FirstOrDefault(rec => rec.Id == Model.Id);
if (Ingredient == null)
return null;
Context.Ingredients.Remove(Ingredient);
Context.SaveChanges();
return Ingredient.ViewModel;
}
}
}