108 lines
3.5 KiB
C#
108 lines
3.5 KiB
C#
using SushiContracts.BindingModels;
|
|
using SushiContracts.SearchModels;
|
|
using SushiContracts.StoragesContracts;
|
|
using SushiContracts.ViewModels;
|
|
using SushiShopDatabaseImplement.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using SushiDatabaseImplement;
|
|
using SushiDatabaseImplement.Models;
|
|
|
|
namespace SushiShopDatabaseImplement.Implements
|
|
{
|
|
public class SushiStorage : ISushiStorage
|
|
{
|
|
public List<SushiViewModel> GetFullList()
|
|
{
|
|
using var context = new SushiDatabase();
|
|
return context.Sushies
|
|
.Include(x => x.Components)
|
|
.ThenInclude(x => x.Component)
|
|
.ToList()
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
public List<SushiViewModel> GetFilteredList(SushiSearchModel model)
|
|
{
|
|
if (string.IsNullOrEmpty(model.SushiName))
|
|
{
|
|
return new();
|
|
}
|
|
using var context = new SushiDatabase();
|
|
return context.Sushies
|
|
.Include(x => x.Components)
|
|
.ThenInclude(x => x.Component)
|
|
.Where(x => x.SushiName.Contains(model.SushiName))
|
|
.ToList()
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
public SushiViewModel? GetElement(SushiSearchModel model)
|
|
{
|
|
if (string.IsNullOrEmpty(model.SushiName) &&
|
|
!model.Id.HasValue)
|
|
{
|
|
return null;
|
|
}
|
|
using var context = new SushiDatabase();
|
|
return context.Sushies
|
|
.Include(x => x.Components)
|
|
.ThenInclude(x => x.Component)
|
|
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.SushiName) &&
|
|
x.SushiName == model.SushiName) ||
|
|
(model.Id.HasValue && x.Id ==
|
|
model.Id))
|
|
?.GetViewModel;
|
|
}
|
|
public SushiViewModel? Insert(SushiBindingModel model)
|
|
{
|
|
using var context = new SushiDatabase();
|
|
var newSushi = Sushi.Create(context, model);
|
|
if (newSushi == null)
|
|
{
|
|
return null;
|
|
}
|
|
context.Sushies.Add(newSushi);
|
|
context.SaveChanges();
|
|
return newSushi.GetViewModel;
|
|
}
|
|
public SushiViewModel? Update(SushiBindingModel model)
|
|
{
|
|
using var context = new SushiDatabase();
|
|
using var transaction = context.Database.BeginTransaction();
|
|
try
|
|
{
|
|
var Sushi = context.Sushies.FirstOrDefault(rec =>
|
|
rec.Id == model.Id);
|
|
if (Sushi == null)
|
|
{
|
|
return null;
|
|
}
|
|
Sushi.Update(model);
|
|
context.SaveChanges();
|
|
Sushi.UpdateComponents(context, model);
|
|
transaction.Commit();
|
|
return Sushi.GetViewModel;
|
|
}
|
|
catch
|
|
{
|
|
transaction.Rollback();
|
|
throw;
|
|
}
|
|
}
|
|
public SushiViewModel? Delete(SushiBindingModel model)
|
|
{
|
|
using var context = new SushiDatabase();
|
|
var element = context.Sushies
|
|
.Include(x => x.Components)
|
|
.FirstOrDefault(rec => rec.Id == model.Id);
|
|
if (element != null)
|
|
{
|
|
context.Sushies.Remove(element);
|
|
context.SaveChanges();
|
|
return element.GetViewModel;
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
}
|