PIbd-21_Bakalskaya_E.D._Sus.../SushiBarDatabaseImplement/Implements/OrderStorage.cs

96 lines
3.2 KiB
C#
Raw Normal View History


using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Orders.Select(x => AccessViewModel(x.GetViewModel)).ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new SecuritySystemDatabase();
var orders = context.Orders
.Include(x => x.Secure)
.Select(x => x.GetViewModel)
.ToList();
if (model.Id.HasValue)
{
orders = orders.Where(x => x.Id == model.Id.Value).ToList();
}
if (model.DateFrom.HasValue)
{
orders = orders.Where(x => x.DateCreate >= model.DateFrom.Value).ToList();
}
if (model.DateTo.HasValue)
{
orders = orders.Where(x => x.DateCreate <= model.DateTo.Value).ToList();
}
return orders;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new SushiBarDatabase();
return AccessViewModel(context.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id).GetViewModel);
}
public OrderViewModel? Insert(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
context.Orders.Add(newOrder);
context.SaveChanges();
return AccessViewModel(newOrder.GetViewModel);
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return AccessViewModel(order.GetViewModel);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null) return null;
context.Remove(order);
context.SaveChanges();
return AccessViewModel(order.GetViewModel);
}
public static OrderViewModel? AccessViewModel(OrderViewModel viewModel)
{
using var context = new SushiBarDatabase();
var sushi = context.Sushis.FirstOrDefault(x => x.Id == viewModel.SushiId);
if (viewModel != null)
{
viewModel.SushiName = sushi!.SushiName;
return viewModel;
}
return null;
}
}
}