Coursach/Course/DatabaseImplement/Implements/WorkshopStorage.cs

71 lines
2.3 KiB
C#

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StoragesContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace DatabaseImplement.Implements
{
public class WorkshopStorage : IWorkshopStorage
{
public WorkshopViewModel? Delete(WorkshopBindingModel model)
{
using var context = new FactoryGoWorkDatabase();
var newWorkshop = context.Workshops.FirstOrDefault(x => x.Id == model.Id);
if (newWorkshop == null)
return null;
newWorkshop.UpdateWorkers(context, model);
context.Workshops.Remove(newWorkshop);
context.SaveChanges();
return newWorkshop.GetViewModel;
}
public WorkshopViewModel? GetElement(WorkshopSearchModel model)
{
using var context = new FactoryGoWorkDatabase();
return context.Workshops.Include(x => x.Workers).ThenInclude(x => x.Worker).FirstOrDefault(x => (!string.IsNullOrEmpty(model.Title) && x.Title.Contains(model.Title)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<WorkshopViewModel> GetFilteredList(WorkshopSearchModel model)
{
if (!model.UserId.HasValue)
{
return new();
}
using var context = new FactoryGoWorkDatabase();
return context.Workshops.Include(x => x.Workers).ThenInclude(x => x.Worker).Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList();
}
public List<WorkshopViewModel> GetFullList()
{
using var context = new FactoryGoWorkDatabase();
return context.Workshops.Include(x => x.Workers).ThenInclude(x => x.Worker).Select(x => x.GetViewModel).ToList();
}
public WorkshopViewModel? Insert(WorkshopBindingModel model)
{
using var context = new FactoryGoWorkDatabase();
var newWorkshop = Workshop.Create(context, model);
if (newWorkshop == null)
return null;
context.Workshops.Add(newWorkshop);
context.SaveChanges();
return newWorkshop.GetViewModel;
}
public WorkshopViewModel? Update(WorkshopBindingModel model)
{
using var context = new FactoryGoWorkDatabase();
var newWorkshop = context.Workshops.FirstOrDefault(x => x.Id == model.Id);
if (newWorkshop == null)
return null;
newWorkshop.Update(model);
newWorkshop.UpdateWorkers(context, model);
context.SaveChanges();
return newWorkshop.GetViewModel;
}
}
}