CourseWorkElectronicsShop/ElectronicsShop/ElectronicsShopDataBaseImplement/Implements/ClientStorage.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 ClientStorage : IClientStorage
{
public ClientViewModel? Delete(ClientBindingModel model)
{
using var context = new Database();
var element = context.Clients.FirstOrDefault(rec => rec.ID == model.ID);
if (element != null)
{
context.Clients.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.Email) && !model.ID.HasValue)
{
return null;
}
using var context = new Database();
return context.Clients.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Email) && x.Email == model.Email ||
(model.ID.HasValue && x.ID == model.ID)))?.GetViewModel;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.Email))
{
return new();
}
using var context = new Database();
return context.Clients.Where(x => x.Email.Contains(model.Email)).Select(x => x.GetViewModel).ToList();
}
public List<ClientViewModel> GetFullList()
{
using var context = new Database();
return context.Clients.Select(x => x.GetViewModel).ToList();
}
public ClientViewModel? Insert(ClientBindingModel model)
{
var newComponent = Client.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new Database();
context.Clients.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
using var context = new Database();
var component = context.Clients.FirstOrDefault(x => x.ID == model.ID);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}