PIbd-21_BatylkinaAO_MusoevD.../Canteen/CanteenDatabaseImplement/Implements/OrderStorage.cs

127 lines
3.8 KiB
C#

using CanteenContracts.BindingModels;
using CanteenContracts.SearchModel;
using CanteenContracts.SearchModels;
using CanteenContracts.StoragesContracts;
using CanteenContracts.View;
using CanteenContracts.ViewModels;
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 OrderStorage : IOrderStorage
{
public OrderCookViewModel? GetOrderCookElement(OrderCookSearchModel model)
{
if (!model.Id.HasValue && (!model.OrderId.HasValue || !model.CookId.HasValue))
{
return null;
}
using var context = new CanteenDatabase();
return context.OrderCook
.FirstOrDefault(x => x.OrderId == model.OrderId && x.CookId == model.CookId)?.GetViewModel;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new CanteenDatabase();
return context.Orders
.Include(x => x.Cooks)
.ThenInclude(x => x.Cook)
.Include(x => x.Tablewares)
.ThenInclude(x => x.Tableware)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?
.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.VisitorId.HasValue)
{
return new();
}
using var context = new CanteenDatabase();
return context.Orders
.Include(x => x.Cooks)
.ThenInclude(x => x.Cook)
.Include(x => x.Tablewares)
.ThenInclude(x => x.Tableware)
.Where(x => (model.Id.HasValue && x.Id == model.Id) || (model.VisitorId.HasValue && model.VisitorId == x.VisitorId)).Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new CanteenDatabase();
return context.Orders
.Include(x => x.Cooks)
.ThenInclude(x => x.Cook)
.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new CanteenDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new CanteenDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
if (model.OrderTablewares.Any()) order.UpdateOrderTablewares(context, model);
if (model.OrderCooks.Any()) order.UpdateOrderCook(context, model);
return order.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new CanteenDatabase();
var client = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
context.Orders.Remove(client);
context.SaveChanges();
return client.GetViewModel;
}
}
}