PIbd-21_Medvedkov_Coursach/ComputerShopDatabaseImplement/Implements/ComponentStorage.cs

83 lines
2.5 KiB
C#
Raw Normal View History

2024-05-01 04:42:57 +04:00
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Models;
namespace ComputerShopDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var Context = new ComputerShopDatabase();
return Context.Components
.Select(x => x.ViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel Model)
{
using var Context = new ComputerShopDatabase();
// колмплектующие по пользователям (дополнительно)
return Context.Components
.Where(x => x.UserId == Model.UserId)
.Select(x => x.ViewModel)
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel Model)
{
using var Context = new ComputerShopDatabase();
return Context.Components
.FirstOrDefault(x => x.Id == Model.Id)?
.ViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var NewComponent = Component.Create(Model);
Context.Components.Add(NewComponent);
Context.SaveChanges();
return NewComponent.ViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var ExistingComponent = Context.Components.FirstOrDefault(x => x.Id == Model.Id);
if (ExistingComponent == null)
{
return null;
}
ExistingComponent.Update(Model);
Context.SaveChanges();
return ExistingComponent.ViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var ExistingComponent = Context.Components.FirstOrDefault(x => x.Id == Model.Id);
if (ExistingComponent == null)
{
return null;
}
Context.Components.Remove(ExistingComponent);
Context.SaveChanges();
return ExistingComponent.ViewModel;
}
}
}