CourseWorkElectronicsShop/ElectronicsShop/ElectronicsShopDataBaseImplement/Implements/RoleStorage.cs

83 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
{
public class RoleStorage: IRoleStorage
{
public RoleViewModel? Delete(RoleBindingModel model)
{
using var context = new Database();
var element = context.Roles.FirstOrDefault(rec => rec.ID == model.ID);
if (element != null)
{
context.Roles.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public RoleViewModel? GetElement(RoleSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.ID.HasValue)
{
return null;
}
using var context = new Database();
return context.Roles.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Name) && x.Name == model.Name && (model.ID.HasValue && x.ID == model.ID)))?.GetViewModel;
}
public List<RoleViewModel> GetFilteredList(RoleSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new Database();
return context.Roles.Where(x => x.Name.Contains(model.Name)).Select(x => x.GetViewModel).ToList();
}
public List<RoleViewModel> GetFullList()
{
using var context = new Database();
return context.Roles.Select(x => x.GetViewModel).ToList();
}
public RoleViewModel? Insert(RoleBindingModel model)
{
var newComponent = Role.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new Database();
context.Roles.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public RoleViewModel? Update(RoleBindingModel model)
{
using var context = new Database();
var component = context.Roles.FirstOrDefault(x => x.ID == model.ID);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}