ComputerHardwareStore_YouAr.../ComputerHardwareStore/ComputerHardwareStoreDatabaseImplement/Implements/ComponentStorage.cs

85 lines
2.9 KiB
C#
Raw Normal View History

2024-04-30 20:27:11 +04:00
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
2024-04-30 20:42:42 +04:00
.Select(c => c.GetViewModel)
2024-04-30 20:27:11 +04:00
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
2024-04-30 20:42:42 +04:00
return new();
2024-04-30 20:27:11 +04:00
}
using var context = new ComputerHardwareStoreDBContext();
return context.Components
2024-04-30 20:42:42 +04:00
.Where(c => c.Name.Contains(model.Name))
.Select(c => c.GetViewModel)
2024-04-30 20:27:11 +04:00
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new ComputerHardwareStoreDBContext();
return context.Components
2024-04-30 20:42:42 +04:00
.FirstOrDefault(c =>
(!string.IsNullOrEmpty(model.Name) && c .Name == model.Name) ||
(model.Id.HasValue && c.Id == model.Id))
2024-04-30 20:27:11 +04:00
?.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 element = context.Components.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
2024-04-30 20:27:11 +04:00
{
return null;
}
element.Update(model);
2024-04-30 20:27:11 +04:00
context.SaveChanges();
return element.GetViewModel;
2024-04-30 20:27:11 +04:00
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new ComputerHardwareStoreDBContext();
2024-04-30 20:42:42 +04:00
var element = context.Components.FirstOrDefault(c => c.Id == model.Id);
if (element == null)
2024-04-30 20:27:11 +04:00
{
2024-04-30 20:42:42 +04:00
return null;
2024-04-30 20:27:11 +04:00
}
2024-04-30 20:42:42 +04:00
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
2024-04-30 20:27:11 +04:00
}
}
}