SUBD_Aleikin/Restaurant/RestaurantDatabaseImplement/Implements/OrderStorage.cs

126 lines
4.2 KiB
C#

using Microsoft.EntityFrameworkCore;
using RestaurantContracts.BindingModels;
using RestaurantContracts.SearchModels;
using RestaurantContracts.StoragesContracts;
using RestaurantContracts.ViewModels;
using RestaurantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RestaurantDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new RestaurantDatabase();
return context.Orders
.Include(x => x.Client)
.Include(x => x.Products)
.ThenInclude(x => x.Product)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new RestaurantDatabase();
if (model.Id.HasValue)
{
return context.Orders
.Include(x => x.Products)
.ThenInclude(x => x.ProductId)
.Include(x => x.Client)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ClientId.HasValue)
{
return context.Orders
.Include(x => x.Products)
.ThenInclude(x => x.ProductId)
.Include(x => x.Client)
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.Date.HasValue)
{
return context.Orders
.Include(x => x.Products)
.ThenInclude(x => x.ProductId)
.Include(x => x.Client)
.Where(x => x.Date == model.Date)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
return new();
}
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new RestaurantDatabase();
return context.Orders
.Include(x => x.Client)
.Include(x => x.Products)
.ThenInclude(x => x.Product)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
using var context = new RestaurantDatabase();
var newOrder = Order.Create(context, model);
if (newOrder == null)
{
return null;
}
context.Orders.Add(newOrder);
context.SaveChanges();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new RestaurantDatabase();
var element = context.Orders
.Include(x => x.Client)
.Include(x => x.Products)
.ThenInclude(x => x.ProductId)
.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
return GetElement(new OrderSearchModel { Id = element.Id });
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new RestaurantDatabase();
var element = context.Orders
.Include(x => x.Client)
.Include(x => x.Products)
.ThenInclude(x => x.ProductId)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}