PIbd-21_Pyatakov_KM_Markov_.../UniversityDataBaseImplemet/Implements/RoleStorage.cs

90 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityContracts.ViewModels;
using UniversityDataBaseImplemet.Models;
namespace UniversityDataBaseImplemet.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)
{
using var context = new Database();
if (model.Id.HasValue)
return context.Roles
.FirstOrDefault(record => record.Id == model.Id)
?.GetViewModel;
if (!string.IsNullOrEmpty(model.Name))
return context.Roles
.FirstOrDefault(record => record.Name.Equals(model.Name))
?.GetViewModel;
return null;
}
public List<RoleViewModel> GetFilteredList(RoleSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new Database();
return context.Roles
.Where(record => record.Name.Contains(model.Name))
.Select(record => record.GetViewModel)
.ToList();
}
public List<RoleViewModel> GetFullList()
{
using var context = new Database();
return context.Roles.Select(record => record.GetViewModel).ToList();
}
public RoleViewModel? Insert(RoleBindingModel model)
{
var newRole = Role.Create(model);
if (newRole == null)
{
return null;
}
using var context = new Database();
context.Roles.Add(newRole);
context.SaveChanges();
return newRole.GetViewModel;
}
public RoleViewModel? Update(RoleBindingModel model)
{
using var context = new Database();
var client = context.Roles.FirstOrDefault(record => record.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
}
}