CourseWorkElectronicsShop/ElectronicsShop/ElectronicsShopDataBaseImplement/Implements/UserStorage.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 UserStorage : IUserStorage
{
public UserViewModel? Delete(UserBindingModel model)
{
using var context = new Database();
var element = context.Users.FirstOrDefault(rec => rec.ID == model.ID);
if (element != null)
{
context.Users.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public UserViewModel? GetElement(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Login) && !model.ID.HasValue)
{
return null;
}
using var context = new Database();
return context.Users.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Login) && x.Login == model.Login ||
(model.ID.HasValue && x.ID == model.ID)))?.GetViewModel;
}
public List<UserViewModel> GetFilteredList(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Login))
{
return new();
}
using var context = new Database();
return context.Users.Where(x => x.Login.Contains(model.Login)).Select(x => x.GetViewModel).ToList();
}
public List<UserViewModel> GetFullList()
{
using var context = new Database();
return context.Users.Select(x => x.GetViewModel).ToList();
}
public UserViewModel? Insert(UserBindingModel model)
{
var newComponent = User.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new Database();
context.Users.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public UserViewModel? Update(UserBindingModel model)
{
using var context = new Database();
var component = context.Users.FirstOrDefault(x => x.ID == model.ID);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}