CourseWork_CompShop/ComputerShopProvider/ComputerShopDatabaseImplement/Implements/ComponentStorage.cs

100 lines
3.3 KiB
C#
Raw Normal View History

2023-04-05 19:08:51 +04:00
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopDatabaseImplement.Implements
{
2023-04-07 16:53:49 +04:00
public class ComponentStorage : IComponentStorage
2023-04-05 19:08:51 +04:00
{
public List<ComponentViewModel> GetFullList()
{
using var context = new ComputerShopDatabase();
return context.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel
model)
{
2023-05-17 13:52:06 +04:00
if (string.IsNullOrEmpty(model.ComponentName) && model.ClientId == null)
2023-04-05 19:08:51 +04:00
{
return new();
}
using var context = new ComputerShopDatabase();
2023-05-17 13:52:06 +04:00
if (!string.IsNullOrEmpty(model.ComponentName))
{
return context.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
.Select(x => x.GetViewModel)
.ToList();
}
else
{
return context.Components
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
2023-04-05 19:08:51 +04:00
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
using var context = new ComputerShopDatabase();
return context.Components
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName ==
model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new ComputerShopDatabase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new ComputerShopDatabase();
var component = context.Components.FirstOrDefault(x => x.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 ComputerShopDatabase();
var element = context.Components.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}