CourseWorkElectronicsShop/ElectronicsShop/ElectronicsShopDataBaseImplement/Implements/CostItemStorage.cs

84 lines
2.7 KiB
C#

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
{
public class CostItemStorage : ICostItemStorage
{
public CostItemViewModel? Delete(CostItemBindingModel model)
{
using var context = new Database();
var element = context.CostItems.FirstOrDefault(rec => rec.ID == model.ID);
if (element != null)
{
context.CostItems.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public CostItemViewModel GetElement(CostItemSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.ID.HasValue)
{
return null;
}
using var context = new Database();
return context.CostItems.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Name) && x.Name == model.Name ||
(model.ID.HasValue && x.ID == model.ID)))?.GetViewModel;
}
public List<CostItemViewModel> GetFillteredList(CostItemSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new Database();
return context.CostItems.Where(x => x.Name.Contains(model.Name)).Select(x => x.GetViewModel).ToList();
}
public List<CostItemViewModel> GetFullList()
{
using var context = new Database();
return context.CostItems.Select(x => x.GetViewModel).ToList();
}
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;
}
}
}