113 lines
3.3 KiB
C#
113 lines
3.3 KiB
C#
using Contracts.BindingModels;
|
|
using Contracts.SearchModels;
|
|
using Contracts.StorageContracts;
|
|
using Contracts.ViewModels;
|
|
using DatabaseImplement.Models;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace DatabaseImplement.Implements
|
|
{
|
|
public class CartItemStorage : ICartItemStorage
|
|
{
|
|
public CartItemViewModel? Delete(CartItemBindingModel model)
|
|
{
|
|
using var context = new Database();
|
|
var element = context.CartItems
|
|
.FirstOrDefault(rec => rec.Id == model.Id);
|
|
if (element != null)
|
|
{
|
|
context.CartItems.Remove(element);
|
|
context.SaveChanges();
|
|
return element.GetViewModel;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public CartItemViewModel? GetElement(CartItemSearchModel model)
|
|
{
|
|
if (!model.Id.HasValue)
|
|
{
|
|
return null;
|
|
}
|
|
using var context = new Database();
|
|
return context.CartItems
|
|
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
|
|
}
|
|
|
|
public List<CartItemViewModel> GetFilteredList(CartItemSearchModel model)
|
|
{
|
|
if (model.UserId == Guid.Empty && string.IsNullOrEmpty(model.ProductName))
|
|
{
|
|
return new();
|
|
}
|
|
using var context = new Database();
|
|
if (model.UserId != Guid.Empty)
|
|
{
|
|
return context.CartItems
|
|
.Where(x => x.UserId == model.UserId)
|
|
.ToList()
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
return context.CartItems
|
|
.Where(x => x.ProductName.Contains(model.ProductName))
|
|
.ToList()
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
|
|
public List<CartItemViewModel> GetFullList()
|
|
{
|
|
using var context = new Database();
|
|
return context.CartItems
|
|
.ToList()
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
|
|
public CartItemViewModel? Insert(CartItemBindingModel model)
|
|
{
|
|
using var context = new Database();
|
|
var newItem = CartItem.Create(context, model);
|
|
if (newItem == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
context.CartItems.Add(newItem);
|
|
context.SaveChanges();
|
|
return newItem.GetViewModel;
|
|
}
|
|
|
|
public CartItemViewModel? Update(CartItemBindingModel model)
|
|
{
|
|
using var context = new Database();
|
|
using var transaction = context.Database.BeginTransaction();
|
|
try
|
|
{
|
|
var item = context.CartItems.FirstOrDefault(rec =>
|
|
rec.Id == model.Id);
|
|
|
|
if (item == null)
|
|
{
|
|
return null;
|
|
}
|
|
item.Update(model);
|
|
|
|
context.SaveChanges();
|
|
transaction.Commit();
|
|
return new();
|
|
}
|
|
catch
|
|
{
|
|
transaction.Rollback();
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|