using ForumContracts.BindingModels; using ForumContracts.SearchModels; using ForumContracts.StoragesContracts; using ForumContracts.ViewModels; using BlogDatabase.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlogDatabase.Implements { public class RoleStorage : IRoleStorage { public void RoleInsertList(int num) { Random rnd = new Random(); using var context = new BlogDatabase(); for (int i = 0; i < num; ++i) { var model = new RoleBindingModel { Id = 0, Name = rnd.Next(1000).ToString(), }; context.Roles.Add(Role.Create(model)); } context.SaveChanges(); } public RoleViewModel? Delete(RoleBindingModel model) { using var context = new BlogDatabase(); 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 BlogDatabase(); return context.Roles .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public List GetFilteredList(RoleSearchModel model) { if (string.IsNullOrEmpty(model.Name)) { return new(); } using var context = new BlogDatabase(); return context.Roles .Where(x => x.Name.Contains(model.Name)) .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new BlogDatabase(); return context.Roles .Select(x => x.GetViewModel) .ToList(); } public RoleViewModel? Insert(RoleBindingModel model) { var newRole = Role.Create(model); if (newRole == null) { return null; } using var context = new BlogDatabase(); context.Roles.Add(newRole); context.SaveChanges(); return newRole.GetViewModel; } public RoleViewModel? Update(RoleBindingModel model) { using var context = new BlogDatabase(); var component = context.Roles.FirstOrDefault(x => x.Id == model.Id); if (component == null) { return null; } component.Update(model); context.SaveChanges(); return component.GetViewModel; } } }