PIbd-21_Raspaev_N.I._FoodOr.../FoodOrders/FoodOrdersDatabaseImplement/Implements/OrderStorage.cs

87 lines
2.7 KiB
C#
Raw Normal View History

2023-02-27 21:51:16 +04:00
using FoodOrdersContracts.BindingModels;
using FoodOrdersContracts.SearchModels;
using FoodOrdersContracts.StoragesContracts;
using FoodOrdersContracts.ViewModels;
using FoodOrdersDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace FoodOrdersDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
2023-03-23 18:18:58 +04:00
public List<OrderViewModel> GetFullList()
2023-02-27 21:51:16 +04:00
{
using var context = new FoodOrdersDatabase();
return context.Orders
2023-03-23 18:18:58 +04:00
.Include(x => x.Dish)
.Select(x => x.GetViewModel)
.ToList();
2023-02-27 21:51:16 +04:00
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new FoodOrdersDatabase();
return context.Orders
2023-03-23 18:18:58 +04:00
.Include(x => x.Dish)
2023-02-27 21:51:16 +04:00
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
2023-03-23 18:18:58 +04:00
public OrderViewModel? GetElement(OrderSearchModel model)
2023-02-27 21:51:16 +04:00
{
2023-03-23 18:18:58 +04:00
if (!model.Id.HasValue)
{
return null;
}
2023-02-27 21:51:16 +04:00
using var context = new FoodOrdersDatabase();
return context.Orders
2023-03-23 18:18:58 +04:00
.Include(x => x.Dish)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
2023-02-27 21:51:16 +04:00
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new FoodOrdersDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new FoodOrdersDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
2023-03-23 18:18:58 +04:00
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new FoodOrdersDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
2023-02-27 21:51:16 +04:00
}
}