PIbd-21_BatylkinaAO_MusoevD.../Canteen/CanteenDatabaseImplement/Implements/DishStorage.cs
2023-05-18 00:40:11 +03:00

134 lines
4.0 KiB
C#

using CanteenContracts.BindingModels;
using CanteenContracts.SearchModel;
using CanteenContracts.StoragesContracts;
using CanteenContracts.View;
using CanteenDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenDatabaseImplement.Implements
{
public class DishStorage : IDishStorage
{
public DishViewModel? GetElement(DishSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new CanteenDatabase();
return context.Dishes
.Include(x => x.Products)
.ThenInclude(x => x.Product)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.DishName) && x.DishName == model.DishName) || (model.Id.HasValue && x.Id == model.Id)
)?.GetViewModel;
}
public List<DishViewModel> GetFilteredList(DishSearchModel model)
{
if (string.IsNullOrEmpty(model.DishName) && !model.ManagerId.HasValue)
{
return new();
}
using var context = new CanteenDatabase();
return context.Dishes
.Include(x => x.Products)
.ThenInclude(x => x.Product)
.Where(x => x.DishName == model.DishName || (model.ManagerId.HasValue && model.ManagerId == x.ManagerId)).Select(x => x.GetViewModel).ToList();
}
public List<DishViewModel> GetFullList()
{
using var context = new CanteenDatabase();
return context.Dishes.Include(x => x.Products).ThenInclude(x => x.Product).Select(x => x.GetViewModel).ToList();
}
public DishViewModel? Insert(DishBindingModel model)
{
using var context = new CanteenDatabase();
using var transaction = context.Database.BeginTransaction();
{
try
{
var newDish = Dish.Create(context, model);
if (newDish == null)
{
transaction.Rollback();
return null;
}
context.Dishes.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 CanteenDatabase();
using var transaction = context.Database.BeginTransaction();
{
try
{
var dish = context.Dishes.FirstOrDefault(x => x.Id == model.Id);
if (dish == null)
{
transaction.Rollback();
return null;
}
dish.Update(model);
context.SaveChanges();
if (model.DishProducts != null)
dish.UpdateDishProduct(context, model);
context.Database.CommitTransaction();
return dish.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
return null;
}
}
}
public DishViewModel? Delete(DishBindingModel model)
{
using var context = new CanteenDatabase();
var element = context.Dishes.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Dishes.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}