SYBD_2024/ConstructionFirmDatabaseImplement/Implements/ConstructionMaterialStorage.cs

73 lines
2.8 KiB
C#

using ConstructionFirmDatabaseImplement.Models;
using Subd_4.BindingModels;
using Subd_4.SearchModels;
using Subd_4.StoragesContracts;
using Subd_4.ViewModels;
namespace ConstructionFirmDatabaseImplement.Implements
{
public class ConstructionMaterialStorage : IConstructionMaterialStorage
{
public List<ConstructionMaterialViewModel> GetFilteredList(ConstructionMaterialSearchModel model)
{
if (string.IsNullOrEmpty(model.MaterialName))
{
return new();
}
using var context = new ConstructionFirmDatabase();
return context.ConstructionMaterials.Where(x => x.MaterialName.Contains(model.MaterialName)).Select(x => x.GetViewModel).ToList();
}
public List<ConstructionMaterialViewModel> GetFullList()
{
using var context = new ConstructionFirmDatabase();
return context.ConstructionMaterials.Select(x => x.GetViewModel).ToList();
}
public ConstructionMaterialViewModel? Delete(ConstructionMaterialBindingModel model)
{
using var context = new ConstructionFirmDatabase();
var element = context.ConstructionMaterials.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.ConstructionMaterials.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ConstructionMaterialViewModel? GetElement(ConstructionMaterialSearchModel model)
{
using var context = new ConstructionFirmDatabase();
return context.ConstructionMaterials.FirstOrDefault(x => (!string.IsNullOrEmpty(model.MaterialName)) && x.MaterialName == model.MaterialName || model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
public ConstructionMaterialViewModel? Insert(ConstructionMaterialBindingModel model)
{
var newConstructionMaterial = ConstructionMaterial.Create(model);
if (newConstructionMaterial == null)
{
return null;
}
using var context = new ConstructionFirmDatabase();
context.ConstructionMaterials.Add(newConstructionMaterial);
context.SaveChanges();
return newConstructionMaterial.GetViewModel;
}
public ConstructionMaterialViewModel? Update(ConstructionMaterialBindingModel model)
{
using var context = new ConstructionFirmDatabase();
var component = context.ConstructionMaterials.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}