PIbd-31_Rodionov.I.A._COP_28/COP/PortalAccountsDatabaseImplement/Implements/RoleStorage.cs
2024-10-22 19:42:03 +04:00

85 lines
2.7 KiB
C#

using PortalAccountsContracts.BindingModels;
using PortalAccountsContracts.SearchModels;
using PortalAccountsContracts.StoragesContracts;
using PortalAccountsContracts.ViewModels;
using PortalAccountsDatabaseImplement.Models;
namespace PortalAccountsDatabaseImplement.Implements
{
public class RoleStorage : IRoleStorage
{
public List<RoleViewModel> GetFullList()
{
using var context = new PortalAccountsDatabase();
return context.Roles
.Select(x => x.GetViewModel)
.ToList();
}
public List<RoleViewModel> GetFilteredList(RoleSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new PortalAccountsDatabase();
return context.Roles
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
public RoleViewModel? GetElement(RoleSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new PortalAccountsDatabase();
return context.Roles
.FirstOrDefault(x => !string.IsNullOrEmpty(model.Name) && x.Name == model.Name ||
model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public RoleViewModel? Insert(RoleBindingModel model)
{
var newRole = Role.Create(model);
if (newRole == null)
{
return null;
}
using var context = new PortalAccountsDatabase();
context.Roles.Add(newRole);
context.SaveChanges();
return newRole.GetViewModel;
}
public RoleViewModel? Update(RoleBindingModel model)
{
using var context = new PortalAccountsDatabase();
var role = context.Roles.FirstOrDefault(x => x.Id == model.Id);
if (role == null)
{
return null;
}
role.Update(model);
context.SaveChanges();
return role.GetViewModel;
}
public RoleViewModel? Delete(RoleBindingModel model)
{
using var context = new PortalAccountsDatabase();
var element = context.Roles.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Roles.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}