CourseWorkElectronicsShop/ElectronicsShop/ElectronicsShopDataBaseImplement/Implements/CostItemStorage.cs

82 lines
2.6 KiB
C#
Raw Normal View History

2024-04-29 01:55:20 +04:00
using ElectronicsShopContracts.BindingModels;
using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.StorageContracts;
using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicsShopDataBaseImplement.Implements
{
2024-05-25 13:06:38 +04:00
public class CostItemStorage : ICostItemStorage
2024-04-29 01:55:20 +04:00
{
2024-05-26 17:47:24 +04:00
public CostItemViewModel? Insert(CostItemBindingModel model) {
var newComponent = CostItem.Create(model);
if (newComponent == null) {
return null;
}
using var context = new Database();
context.CostItems.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public CostItemViewModel? Update(CostItemBindingModel model) {
using var context = new Database();
var component = context.CostItems.FirstOrDefault(x => x.ID == model.ID);
if (component == null) {
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public CostItemViewModel? Delete(CostItemBindingModel model)
2024-04-29 01:55:20 +04:00
{
using var context = new Database();
2024-05-25 13:06:38 +04:00
var element = context.CostItems.FirstOrDefault(rec => rec.ID == model.ID);
2024-04-29 01:55:20 +04:00
if (element != null)
{
2024-05-25 13:06:38 +04:00
context.CostItems.Remove(element);
2024-04-29 01:55:20 +04:00
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
2024-05-26 17:47:24 +04:00
public CostItemViewModel? GetElement(CostItemSearchModel model)
2024-04-29 01:55:20 +04:00
{
if (string.IsNullOrEmpty(model.Name) && !model.ID.HasValue)
{
return null;
}
using var context = new Database();
2024-05-26 17:47:24 +04:00
return context.CostItems
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name)
&& x.Name == model.Name) ||
(model.ID.HasValue && x.ID == model.ID))?.GetViewModel;
2024-04-29 01:55:20 +04:00
}
2024-05-25 13:06:38 +04:00
public List<CostItemViewModel> GetFillteredList(CostItemSearchModel model)
2024-04-29 01:55:20 +04:00
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new Database();
2024-05-26 17:47:24 +04:00
return context.CostItems.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel).ToList();
2024-04-29 01:55:20 +04:00
}
2024-05-25 13:06:38 +04:00
public List<CostItemViewModel> GetFullList()
2024-04-29 01:55:20 +04:00
{
using var context = new Database();
2024-05-25 13:06:38 +04:00
return context.CostItems.Select(x => x.GetViewModel).ToList();
2024-04-29 01:55:20 +04:00
}
}
}