PIbd-21_BatylkinaAO_MusoevD.../Canteen/CanteenDatabaseImplement/Implements/OrderStorage.cs
2023-05-19 03:39:58 +04:00

120 lines
3.4 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)
.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)
.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 client = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.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;
}
}
}