PIbd-23_Yakobchuk_S.V._SUBD/ConstructionCompany/ConstructionCompanyDatabaseImplement/Implements/ConstructionStorage.cs

81 lines
2.9 KiB
C#
Raw Normal View History

2024-04-22 15:11:47 +04:00
using ConstructionCompanyContracts.BindingModels;
using ConstructionCompanyContracts.SearchModels;
using ConstructionCompanyContracts.StoragesContracts;
using ConstructionCompanyContracts.ViewModels;
using ConstructionCompanyDatabaseImplement.Models;
namespace ConstructionCompanyDatabaseImplement.Implements
{
public class ConstructionStorage : IConstructionStorage
{
public List<ConstructionViewModel> GetFullList()
{
using var context = new ConstructionCompanyDatabase();
return context.Constructions.Select(x => x.GetViewModel).ToList();
}
public List<ConstructionViewModel> GetFilteredList(ConstructionSearchModel model)
{
if (string.IsNullOrEmpty(model.Model))
{
return new();
}
using var context = new ConstructionCompanyDatabase();
return context.Constructions.Where(x => x.Model.Contains(model.Model)).Select(x => x.GetViewModel).ToList();
}
public ConstructionViewModel? GetElement(ConstructionSearchModel model)
{
if (string.IsNullOrEmpty(model.Model) && !model.Id.HasValue)
{
return null;
}
using var context = new ConstructionCompanyDatabase();
return context.Constructions.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Model) && x.Model == model.Model) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ConstructionViewModel? Insert(ConstructionBindingModel model)
{
var newComponent = Construction.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new ConstructionCompanyDatabase();
context.Constructions.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ConstructionViewModel? Update(ConstructionBindingModel model)
{
using var context = new ConstructionCompanyDatabase();
var component = context.Constructions.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public ConstructionViewModel? Delete(ConstructionBindingModel model)
{
using var context = new ConstructionCompanyDatabase();
var element = context.Constructions.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Constructions.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}