85 lines
2.9 KiB
C#
85 lines
2.9 KiB
C#
using ComputerHardwareStoreContracts.BindingModels;
|
|
using ComputerHardwareStoreContracts.SearchModels;
|
|
using ComputerHardwareStoreContracts.StorageContracts;
|
|
using ComputerHardwareStoreContracts.ViewModels;
|
|
using ComputerHardwareStoreDatabaseImplement.Models;
|
|
|
|
namespace ComputerHardwareStoreDatabaseImplement.Implements
|
|
{
|
|
public class ComponentStorage : IComponentStorage
|
|
{
|
|
public List<ComponentViewModel> GetFullList()
|
|
{
|
|
using var context = new ComputerHardwareStoreDBContext();
|
|
return context.Components
|
|
.Select(c => c.GetViewModel)
|
|
.ToList();
|
|
}
|
|
|
|
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
|
|
{
|
|
if (string.IsNullOrEmpty(model.Name))
|
|
{
|
|
return new();
|
|
}
|
|
using var context = new ComputerHardwareStoreDBContext();
|
|
return context.Components
|
|
.Where(c => c.Name.Contains(model.Name))
|
|
.Select(c => c.GetViewModel)
|
|
.ToList();
|
|
}
|
|
|
|
public ComponentViewModel? GetElement(ComponentSearchModel model)
|
|
{
|
|
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
|
|
{
|
|
return null;
|
|
}
|
|
using var context = new ComputerHardwareStoreDBContext();
|
|
return context.Components
|
|
.FirstOrDefault(c =>
|
|
(!string.IsNullOrEmpty(model.Name) && c .Name == model.Name) ||
|
|
(model.Id.HasValue && c.Id == model.Id))
|
|
?.GetViewModel;
|
|
}
|
|
|
|
public ComponentViewModel? Insert(ComponentBindingModel model)
|
|
{
|
|
using var context = new ComputerHardwareStoreDBContext();
|
|
var newComponent = Component.Create(context, model);
|
|
if (newComponent == null)
|
|
{
|
|
return null;
|
|
}
|
|
context.Components.Add(newComponent);
|
|
context.SaveChanges();
|
|
return newComponent.GetViewModel;
|
|
}
|
|
public ComponentViewModel? Update(ComponentBindingModel model)
|
|
{
|
|
using var context = new ComputerHardwareStoreDBContext();
|
|
var component = context.Components.FirstOrDefault(c => c.Id == model.Id);
|
|
if (component == null)
|
|
{
|
|
return null;
|
|
}
|
|
component.Update(model);
|
|
context.SaveChanges();
|
|
return component.GetViewModel;
|
|
}
|
|
|
|
public ComponentViewModel? Delete(ComponentBindingModel model)
|
|
{
|
|
using var context = new ComputerHardwareStoreDBContext();
|
|
var element = context.Components.FirstOrDefault(c => c.Id == model.Id);
|
|
if (element == null)
|
|
{
|
|
return null;
|
|
}
|
|
context.Components.Remove(element);
|
|
context.SaveChanges();
|
|
return element.GetViewModel;
|
|
}
|
|
}
|
|
}
|