PIbd-21_Putincev_D.M._FoodO.../FoodOrders/FoodOrdersDatabaseImplement/Implemets/DishStorage.cs

132 lines
4.2 KiB
C#

using FoodOrdersContracts.BindingModels;
using FoodOrdersContracts.SearchModels;
using FoodOrdersContracts.ViewModels;
using FoodOrdersDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.Xml.Linq;
using FoodOrdersContracts.StoragesContracts;
using System.Runtime.ConstrainedExecution;
namespace FoodOrdersDatabaseImplement.Implements
{
public class DishStorage : IDishStorage
{
public List<DishViewModel> GetFullList()
{
using var context = new FoodOrdersDatabase();
return context.Dishs
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<DishViewModel> GetFilteredList(DishSearchModel model)
{
if (string.IsNullOrEmpty(model.DishName))
{
return new();
}
using var context = new FoodOrdersDatabase();
return context.Dishs
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.DishName.Contains(model.DishName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public DishViewModel? GetElement(DishSearchModel model)
{
if (string.IsNullOrEmpty(model.DishName) && !model.Id.HasValue)
{
return null;
}
using var context = new FoodOrdersDatabase();
return context.Dishs.Include(
x => x.Components
).ThenInclude(x => x.Component).FirstOrDefault(x => (
!string.IsNullOrEmpty(model.DishName) &&
x.DishName == model.DishName) || (model.Id.HasValue && x.Id == model.Id)
)?.GetViewModel;
}
public DishViewModel? Insert(DishBindingModel model)
{
using var context = new FoodOrdersDatabase();
using var transaction = context.Database.BeginTransaction();
{
try
{
var newDish = Dish.Create(context, model);
if (newDish == null)
{
transaction.Rollback();
return null;
}
context.Dishs.Add(newDish);
context.SaveChanges();
context.Database.CommitTransaction();
return newDish.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
return null;
}
}
}
public DishViewModel? Update(DishBindingModel model)
{
using var context = new FoodOrdersDatabase();
using var transaction = context.Database.BeginTransaction();
{
try
{
var Dish = context.Dishs.FirstOrDefault(x => x.Id == model.Id);
if (Dish == null)
{
transaction.Rollback();
return null;
}
Dish.Update(model);
Dish.UpdateComponents(context, model);
context.SaveChanges();
context.Database.CommitTransaction();
return Dish.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
return null;
}
}
}
public DishViewModel? Delete(DishBindingModel model)
{
using var context = new FoodOrdersDatabase();
var element = context.Dishs.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Dishs.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}