PIbd-21_Medvedkov_Coursach/ComputerShopDatabaseImplement/Implements/BatchStorage.cs
2024-05-01 04:42:57 +04:00

112 lines
2.8 KiB
C#

using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopDatabaseImplement.Implements
{
public class BatchStorage : IBatchStorage
{
public List<BatchViewModel> GetFullList()
{
using var context = new ComputerShopDatabase();
return context.Batchs
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<BatchViewModel> GetFilteredList(BatchSearchModel model)
{
using var context = new ComputerShopDatabase();
//сортировка партий по дате
if (model.DateFrom.HasValue && model.DateTo.HasValue)
{
return context.Batchs
.Where(x => (x.DateBatch >= model.DateFrom && x.DateBatch <= model.DateTo))
.Select(x => x.GetViewModel)
.ToList();
}
//партии по товарам
return context.Batchs
.Where(x => x.ProductId == model.ProductId)
.Select(x => x.GetViewModel)
.ToList();
}
public BatchViewModel? GetElement(BatchSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new ComputerShopDatabase();
return context.Batchs
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public BatchViewModel? Insert(BatchBindingModel model)
{
using var context = new ComputerShopDatabase();
var newBatch = Batch.Create(context, model);
if (newBatch == null)
{
return null;
}
context.Batchs.Add(newBatch);
context.SaveChanges();
return newBatch.GetViewModel;
}
public BatchViewModel? Update(BatchBindingModel model)
{
using var context = new ComputerShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var batch = context.Batchs.FirstOrDefault(x => x.Id == model.Id);
if (batch == null)
{
return null;
}
batch.Update(model);
context.SaveChanges();
transaction.Commit();
return context.Batchs
.FirstOrDefault(x => x.Id == model.Id)?
.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public BatchViewModel? Delete(BatchBindingModel model)
{
using var context = new ComputerShopDatabase();
var batch = context.Batchs.FirstOrDefault(y => y.Id == model.Id);
if (batch != null)
{
context.Batchs.Remove(batch);
context.SaveChanges();
return batch.GetViewModel;
}
return null;
}
}
}