PIbd-21_Balberova_D.N._Sush.../SushiBar/SushiBarDatabaseImplement/Implements/IngredientStorage.cs
2023-02-27 22:16:28 +04:00

84 lines
2.9 KiB
C#

using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement.Implements
{
public class IngredientStorage : IIngredientStorage
{
public List<IngredientViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Ingredients
.Select(x => x.GetViewModel)
.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.GetViewModel)
.ToList();
}
public IngredientViewModel? GetElement(IngredientSearchModel model)
{
if (string.IsNullOrEmpty(model.IngredientName) && !model.Id.HasValue)
{
return null;
}
using var context = new SushiBarDatabase();
return context.Ingredients
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.IngredientName) && x.IngredientName == model.IngredientName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
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.GetViewModel;
}
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.GetViewModel;
}
public IngredientViewModel? Delete(IngredientBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.Ingredients.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Ingredients.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}