SushiBarBase/SushiBar/SushiBarDatabaseImplement/Implements/OrderStorage.cs
2024-06-17 22:01:18 +04:00

109 lines
4.1 KiB
C#

using Microsoft.EntityFrameworkCore;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
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
.Include(o => o.Sushi)
.Include(o => o.Client)
.Include(o => o.Implementer)
.Select(o => o.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new SushiBarDatabase();
return context.Orders
.Include(o => o.Sushi)
.Include(o => o.Client)
.Include(o => o.Implementer)
.Where(o =>
(!model.Id.HasValue || o.Id == model.Id) &&
(!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || o.DateCreate <= model.DateTo) &&
(!model.ClientId.HasValue || o.ClientId == model.ClientId) &&
(!model.Status.HasValue || o.Status == model.Status))
.Select(o => o.GetViewModel)
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
using var context = new SushiBarDatabase();
return context.Orders
.Include(o => o.Sushi)
.Include(o => o.Client)
.Include(o => o.Implementer)
.FirstOrDefault(o =>
(!model.Id.HasValue || o.Id == model.Id) &&
(!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || o.DateCreate <= model.DateTo) &&
(!model.ClientId.HasValue || o.ClientId == model.ClientId) &&
(!model.Status.HasValue || o.Status == model.Status))?
.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
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 SushiBarDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var order = context.Orders
.Include(o => o.Sushi)
.Include(o => o.Client)
.Include(o => o.Implementer)
.FirstOrDefault(o => o.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
transaction.Commit();
return order.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.Orders
.Include(o => o.Sushi)
.Include(o => o.Client)
.Include(o => o.Implementer)
.FirstOrDefault(o => o.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}