SUBD_Labs/BeautySalonDatabaseImplement/Implements/MasterStorage.cs

105 lines
3.5 KiB
C#

using BeautySalonContracts.BindingModels;
using BeautySalonContracts.SearchModels;
using BeautySalonContracts.StoragesContracts;
using BeautySalonContracts.ViewModels;
using BeautySalonDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace BeautySalonDatabaseImplement.Implements
{
public class MasterStorage : IMasterStorage
{
public List<MasterViewModel> GetFullList()
{
using var context = new BeautySalonDatabase();
return context.Masters
.Include(x => x.Services)
.ThenInclude(x => x.Service)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<MasterViewModel> GetFilteredList(MasterSearchModel model)
{
if (string.IsNullOrEmpty(model.MasterFIO))
{
return new();
}
using var context = new BeautySalonDatabase();
return context.Masters
.Include(x => x.Services)
.ThenInclude(x => x.Service)
.Where(x => x.MasterFIO.Contains(model.MasterFIO))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public MasterViewModel? GetElement(MasterSearchModel model)
{
if (string.IsNullOrEmpty(model.MasterFIO) &&
!model.Id.HasValue)
{
return null;
}
using var context = new BeautySalonDatabase();
return context.Masters
.Include(x => x.Services)
.ThenInclude(x => x.Service)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.MasterFIO) &&
x.MasterFIO == model.MasterFIO) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public MasterViewModel? Insert(MasterBindingModel model)
{
using var context = new BeautySalonDatabase();
var newMaster = Master.Create(context, model);
if (newMaster == null)
{
return null;
}
context.Masters.Add(newMaster);
context.SaveChanges();
return newMaster.GetViewModel;
}
public MasterViewModel? Update(MasterBindingModel model)
{
using var context = new BeautySalonDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var engine = context.Masters.FirstOrDefault(rec =>
rec.Id == model.Id);
if (engine == null)
{
return null;
}
engine.Update(model);
context.SaveChanges();
engine.UpdateServices(context, model);
transaction.Commit();
return engine.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public MasterViewModel? Delete(MasterBindingModel model)
{
using var context = new BeautySalonDatabase();
var element = context.Masters
.Include(x => x.Services)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Masters.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}