ComputerHardwareStore_YouAr.../ComputerHardwareStore/ComputerHardwareStoreDatabaseImplement/Implements/Vendor.cs

85 lines
2.9 KiB
C#

using ComputerHardwareStoreContracts.BindingModels;
using ComputerHardwareStoreContracts.SearchModels;
using ComputerHardwareStoreContracts.StorageContracts;
using ComputerHardwareStoreContracts.ViewModels;
using ComputerHardwareStoreDatabaseImplement.Models;
namespace ComputerHardwareStoreDatabaseImplement.Implements
{
public class VendorStorage : IVendorStorage
{
public VendorViewModel? GetElement(VendorSearchModel model)
{
if (string.IsNullOrEmpty(model.Login) && !model.Id.HasValue)
{
return null;
}
using var context = new ComputerHardwareStoreDBContext();
return context.Vendors
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Login)
&& x.Login == model.Login)
|| (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<VendorViewModel> GetFilteredList(VendorSearchModel model)
{
if (string.IsNullOrEmpty(model.Login))
{
return new();
}
using var context = new ComputerHardwareStoreDBContext();
return context.Vendors
.Where(x => x.Login.Contains(model.Login))
.Select(x => x.GetViewModel)
.ToList();
}
public List<VendorViewModel> GetFullList()
{
using var context = new ComputerHardwareStoreDBContext();
return context.Vendors
.Select(x => x.GetViewModel)
.ToList();
}
public VendorViewModel? Insert(VendorBindingModel model)
{
using var context = new ComputerHardwareStoreDBContext();
var newVendor = Vendor.Create(context, model);
if (newVendor == null)
{
return null;
}
context.Vendors.Add(newVendor);
context.SaveChanges();
return newVendor.GetViewModel;
}
public VendorViewModel? Update(VendorBindingModel model)
{
using var context = new ComputerHardwareStoreDBContext();
var element = context.Vendors.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
return element.GetViewModel;
}
public VendorViewModel? Delete(VendorBindingModel model)
{
using var context = new ComputerHardwareStoreDBContext();
var element = context.Vendors.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Vendors.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}