PIbd-23-Yunusov-N.N.-CarRep.../CarRepairShop/CarRepairShopDatabaseImplement/Implements/OrderStorage.cs
2024-03-14 18:53:30 +04:00

95 lines
3.1 KiB
C#

using CarRepairShopContracts.BindingModels;
using CarRepairShopContracts.SearchModels;
using CarRepairShopContracts.StoragesContracts;
using CarRepairShopContracts.ViewModels;
using CarRepairShopDatabaseImplement.Models;
namespace CarRepairShopDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new RepairsShopDatabase();
return context.Orders
.Select(x => AccessRepairsStorage(x.GetViewModel))
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new RepairsShopDatabase();
return context.Orders
.Where(x => x.Id == model.Id)
.Select(x => AccessRepairsStorage(x.GetViewModel))
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new RepairsShopDatabase();
return AccessRepairsStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel);
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new RepairsShopDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return AccessRepairsStorage(newOrder.GetViewModel);
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new RepairsShopDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id ==
model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return AccessRepairsStorage(order.GetViewModel);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new RepairsShopDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return AccessRepairsStorage(element.GetViewModel);
}
return null;
}
public static OrderViewModel AccessRepairsStorage(OrderViewModel model)
{
if (model == null)
return null;
using var context = new RepairsShopDatabase();
foreach (var Repairs in context.Repairs)
{
if (Repairs.Id == model.RepairId)
{
model.RepairName = Repairs.RepairName;
break;
}
}
return model;
}
}
}