SushiBarBase/SushiBar/SushiBarDatabaseImplement/Implements/OrderStorage.cs
2024-03-14 13:21:05 +04:00

91 lines
2.9 KiB
C#

using Microsoft.EntityFrameworkCore;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
using System.Collections.Generic;
namespace SushiBarDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Orders
.ToList()
.Select(x => x.GetViewModel(context))
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
var element = GetElement(model);
if (element != null)
{
result.Add(element);
}
return new();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new SushiBarDatabase();
return context.Orders
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel(context);
}
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(context);
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var order = context.Orders.FirstOrDefault(rec =>
rec.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
transaction.Commit();
return order.GetViewModel(context);
}
catch
{
transaction.Rollback();
throw;
}
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.Orders
.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel(context);
}
return null;
}
}
}