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

102 lines
3.7 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)
{
if (!model.Id.HasValue && !model.DateTo.HasValue && !model.DateFrom.HasValue && !model.ClientId.HasValue)
{
return new();
}
using var context = new SushiBarDatabase();
if (model.Id.HasValue)
return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessViewModel(x.GetViewModel)).ToList();
if (model.ClientId.HasValue)
return context.Orders.Where(x => x.ClientId == model.ClientId).Select(x => AccessViewModel(x.GetViewModel)).ToList();
else
return context.Orders.Where(x => x.DateCreate >= model.DateFrom).Where(x => x.DateCreate <= model.DateTo).Select(x => AccessViewModel(x.GetViewModel)).ToList();
}
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();
if (viewModel != null)
{
foreach (var sushi in context.Sushis)
{
if(sushi.Id == viewModel.Id)
{
viewModel.SushiName = sushi.SushiName;
break;
}
}
foreach (var client in context.Clients)
{
if(client.Id == viewModel.ClientId)
{
viewModel.ClientFIO = client.ClientFIO;
return viewModel;
}
}
}
return null;
}
}
}