PIAPS_CW/DatabaseImplement/Implements/RoleStorage.cs

90 lines
2.6 KiB
C#
Raw Normal View History

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StorageContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
2024-06-20 04:17:46 +04:00
public class RoleStorage : IRoleStorage
{
public RoleBindingModel? Delete(RoleSearchModel model)
{
if (model.Id is null)
{
return null;
}
2024-06-20 04:17:46 +04:00
var context = new Database();
var role = context.Roles.FirstOrDefault(r => r.Id == model.Id);
if (role is null)
{
return null;
}
2024-06-20 04:17:46 +04:00
context.Remove(role);
context.SaveChanges();
return role.GetBindingModel();
}
2024-06-20 04:17:46 +04:00
public RoleBindingModel? GetElement(RoleSearchModel model)
{
2024-06-22 18:42:35 +04:00
if (model.Id is null && string.IsNullOrWhiteSpace(model?.Name))
2024-06-20 04:17:46 +04:00
{
return null;
}
var context = new Database();
return context.Roles
.FirstOrDefault(r => (model.Id.HasValue && r.Id == model.Id)
|| (!string.IsNullOrWhiteSpace(model.Name) && r.Name.Contains(model.Name)))
?.GetBindingModel();
}
2024-06-20 04:17:46 +04:00
public IEnumerable<RoleBindingModel> GetList(RoleSearchModel? model)
{
var context = new Database();
2024-06-22 18:42:35 +04:00
if (model is null && string.IsNullOrWhiteSpace(model?.Name))
2024-06-20 04:17:46 +04:00
{
return context.Roles.Select(r => r.GetBindingModel());
}
if (model.Id is null)
{
return [];
}
return context.Roles
.Where(r => (model.Id.HasValue && r.Id == model.Id)
|| (!string.IsNullOrWhiteSpace(model.Name) && r.Name.Contains(model.Name)))
.Select(r => r.GetBindingModel());
}
2024-06-20 04:17:46 +04:00
public RoleBindingModel? Insert(RoleBindingModel model)
{
var context = new Database();
var newRole = Models.Role.ToRoleFromBinding(model);
2024-06-20 04:17:46 +04:00
context.Roles.Add(newRole);
context.SaveChanges();
2024-06-20 04:17:46 +04:00
return newRole.GetBindingModel();
}
2024-06-20 04:17:46 +04:00
public RoleBindingModel? Update(RoleBindingModel model)
{
var context = new Database();
var role = context.Roles.FirstOrDefault(r => r.Id == model.Id);
2024-06-20 04:17:46 +04:00
if (role is null)
{
return null;
}
2024-06-20 04:17:46 +04:00
role.Update(model);
2024-06-20 04:17:46 +04:00
context.SaveChanges();
return role.GetBindingModel();
}
}
}