PIAPS_CW/DatabaseImplement/Implements/SaleStorage.cs

114 lines
3.2 KiB
C#
Raw Normal View History

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StorageContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
public class SaleStorage : ISaleStorage
{
public SaleViewModel? Delete(SaleBindingModel model)
{
using var context = new Database();
var element = context.Sales
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Sales.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public SaleViewModel? GetElement(SaleSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new Database();
return context.Sales
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<SaleViewModel> GetFilteredList(SaleSearchModel model)
{
if (string.IsNullOrEmpty(model.Category))
{
return new();
}
using var context = new Database();
return context.Sales
.Where(x => x.Category.Contains(model.Category))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<SaleViewModel> GetFullList()
{
using var context = new Database();
return context.Sales
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public SaleViewModel? Insert(SaleBindingModel model)
{
using var context = new Database();
var newSale = Sale.Create(context, model);
if (newSale == null)
{
return null;
}
foreach (var product in context.Products)
{
if (product.Category == newSale.Category)
{
product.Sale = newSale;
product.SaleId = newSale.Id;
}
}
context.Sales.Add(newSale);
context.SaveChanges();
return newSale.GetViewModel;
}
public SaleViewModel? Update(SaleBindingModel model)
{
using var context = new Database();
using var transaction = context.Database.BeginTransaction();
try
{
var sale = context.Sales.FirstOrDefault(rec =>
rec.Id == model.Id);
if (sale == null)
{
return null;
}
sale.Update(model);
context.SaveChanges();
transaction.Commit();
return new();
}
catch
{
transaction.Rollback();
throw;
}
}
}
}