PIbd-23-Salin-O.A.-IceCream.../IceCreamShop/IceCreamShopDatabaseImplement/Implements/OrderStorage.cs

96 lines
3.2 KiB
C#
Raw Normal View History

2024-03-04 19:46:39 +04:00
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new IceCreamShopDataBase();
return context.Orders
.Select(x => AccessIceCreamStorage(x.GetViewModel))
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new IceCreamShopDataBase();
return context.Orders
.Where(x => x.Id == model.Id)
.Select(x => AccessIceCreamStorage(x.GetViewModel))
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new IceCreamShopDataBase();
return AccessIceCreamStorage(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 IceCreamShopDataBase();
context.Orders.Add(newOrder);
context.SaveChanges();
return AccessIceCreamStorage(newOrder.GetViewModel);
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new IceCreamShopDataBase();
var order = context.Orders.FirstOrDefault(x => x.Id ==
model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return AccessIceCreamStorage(order.GetViewModel);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new IceCreamShopDataBase();
var element = context.Orders.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return AccessIceCreamStorage(element.GetViewModel);
}
return null;
}
public static OrderViewModel AccessIceCreamStorage(OrderViewModel model)
{
if (model == null)
return null;
using var context = new IceCreamShopDataBase();
2024-03-17 11:13:42 +04:00
var iceCream = context.IceCreams.FirstOrDefault(x => (x.Id == model.IceCreamId));
if (iceCream == null)
return model;
model.IceCreamName = iceCream.IceCreamName;
2024-03-04 19:46:39 +04:00
return model;
}
}
}