Coursach/Course/DatabaseImplement/Implements/WorkshopStorage.cs
2024-04-27 22:13:33 +04:00

79 lines
2.3 KiB
C#

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StoragesContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
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;
context.Workshops.Remove(newWorkshop);
context.SaveChanges();
return newWorkshop.GetViewModel;
}
public WorkshopViewModel? GetElement(WorkshopSearchModel model)
{
using var context = new FactoryGoWorkDatabase();
return context.Workshops.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.Id.HasValue && string.IsNullOrEmpty(model.Title) && !model.UserId.HasValue)
{
return new();
}
using var context = new FactoryGoWorkDatabase();
if (model.Id.HasValue)
{
return context.Workshops.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
else if (model.UserId.HasValue)
{
return context.Workshops.Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList();
}
else
{
return context.Workshops.Where(x => model.Title == x.Title).Select(x => x.GetViewModel).ToList();
}
}
public List<WorkshopViewModel> GetFullList()
{
using var context = new FactoryGoWorkDatabase();
return context.Workshops.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);
context.SaveChanges();
return newWorkshop.GetViewModel;
}
}
}