создание абстрактного класса реализации логики хранилища

This commit is contained in:
kotcheshir73 2021-04-05 10:08:49 +04:00
parent 3d17927bce
commit b0675d3e19
14 changed files with 1278 additions and 611 deletions

View File

@ -0,0 +1,225 @@
using DatabaseCore.Models;
using Microsoft.EntityFrameworkCore;
using ModuleTools.BindingModels;
using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using ModuleTools.Interfaces;
using ModuleTools.Models;
using ModuleTools.ViewModels;
using System;
using System.Linq;
namespace DatabaseCore
{
public abstract class AbstractGenerticEntityService<G, S, T, L, E> : IGenerticEntityService<G, S>
where G : GetBindingModel
where S : SetBindingModel
where T : BaseEntity
where L : ListViewModel<E>, new()
where E : ElementViewModel
{
public OperationResultModel Create(S model)
{
using var context = DatabaseManager.GetContext;
var result = AdditionalCheckingWhenAdding(context, model);
if (!result.IsSucceeded)
{
return result;
}
var exsistEntity = GetUniqueEntity(model, context);
if (exsistEntity == null)
{
var entity = Mapper.MapToClass<S, T>(model, true);
context.Set<T>().Add(entity);
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, true));
}
else
{
if (exsistEntity.IsDeleted)
{
exsistEntity = Mapper.MapToClass(model, exsistEntity, true);
exsistEntity.IsDeleted = false;
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<T, E>(exsistEntity, true));
}
else
{
return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem);
}
}
}
public OperationResultModel Delete(G model)
{
using var context = DatabaseManager.GetContext;
using var transaction = context.Database.BeginTransaction();
try
{
var entity = context.Set<T>().FirstOrDefault(x => x.Id == model.Id);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
var result = AdditionalCheckingWhenDeleting(context, model);
if (!result.IsSucceeded)
{
return result;
}
entity.IsDeleted = true;
entity.DateDelete = DateTime.Now;
context.SaveChanges();
AdditionalDeleting(context, model);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
return OperationResultModel.Success(true);
}
public OperationResultModel Read(G model)
{
int countPages = 0;
using var context = DatabaseManager.GetContext;
// для одной записи
if (model.Id.HasValue)
{
var entity = context.Set<T>().FirstOrDefault(x => x.Id == model.Id.Value);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, model.HaveRight));
}
var query = context.Set<T>().Where(x => !x.IsDeleted).AsQueryable();
query = AdditionalCheckingWhenReadingList(query, model);
query = OrderingWhenReading(query);
if (model.PageNumber.HasValue && model.PageSize.HasValue)
{
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
query = query
.Skip(model.PageSize.Value * model.PageNumber.Value)
.Take(model.PageSize.Value);
}
query = IncludingWhenReading(query);
var result = new L
{
MaxCount = countPages,
List = query.Select(x => Mapper.MapToClass<T, E>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result);
}
public OperationResultModel Update(S model)
{
using var context = DatabaseManager.GetContext;
var result = AdditionalCheckingWhenUpdateing(context, model);
if (!result.IsSucceeded)
{
return result;
}
var exsistEntity = GetUniqueEntity(model, context);
if (exsistEntity != null)
{
return OperationResultModel.Error("Error:", "Существует запись с такими значениями", ResultServiceStatusCode.ExsistItem);
}
var entity = context.Set<T>().FirstOrDefault(x => x.Id == model.Id);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
entity = Mapper.MapToClass(model, entity, true);
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, true));
}
/// <summary>
/// Поиск записи с уникальными значениями
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
protected abstract T GetUniqueEntity(S model, DbContext context);
/// <summary>
/// Возможные дополнительные проверки при добавлении
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
protected abstract OperationResultModel AdditionalCheckingWhenAdding(DbContext context, S model);
/// <summary>
/// Возможные дополнительные проверки при удалении
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
protected abstract OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, G model);
/// <summary>
/// Добавление дополнительных фильтров
/// </summary>
/// <param name="query"></param>
/// <param name="model"></param>
/// <returns></returns>
protected abstract IQueryable<T> AdditionalCheckingWhenReadingList(IQueryable<T> query, G model);
/// <summary>
/// Возможные дополнительные проверки модели при изменении
/// </summary>
/// <param name="model"></param>
protected abstract OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, S model);
/// <summary>
/// Дополнительные удаления зависимых сущностей
/// </summary>
/// <param name="model"></param>
protected abstract void AdditionalDeleting(DbContext context, G model);
/// <summary>
/// Установка сортировок
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
protected abstract IQueryable<T> OrderingWhenReading(IQueryable<T> query);
/// <summary>
/// Добавление Include
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
protected abstract IQueryable<T> IncludingWhenReading(IQueryable<T> query);
}
}

View File

@ -0,0 +1,854 @@
// <auto-generated />
using System;
using DatabaseCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace DatabaseCore.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20210405060128_AddEnviromentSettingsFields")]
partial class AddEnviromentSettingsFields
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.4")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("DatabaseCore.Models.Department.Classroom", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<int>("Capacity")
.HasColumnType("int");
b.Property<int>("ClassroomType")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("EmployeeId")
.HasColumnType("uniqueidentifier");
b.Property<bool>("HaveProjector")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Number")
.HasColumnType("nvarchar(450)");
b.Property<byte[]>("Photo")
.HasColumnType("varbinary(max)");
b.Property<string>("SecurityCode")
.HasColumnType("nvarchar(max)");
b.Property<decimal>("Square")
.HasColumnType("decimal(18,2)");
b.Property<string>("Title")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.HasIndex("Number")
.IsUnique()
.HasFilter("[Number] IS NOT NULL");
b.ToTable("Classrooms");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Discipline", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("DisciplineBlockId")
.HasColumnType("uniqueidentifier");
b.Property<string>("DisciplineBlueAsteriskName")
.HasColumnType("nvarchar(max)");
b.Property<string>("DisciplineName")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("DisciplineShortName")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.HasKey("Id");
b.HasIndex("DisciplineBlockId");
b.HasIndex("DisciplineName")
.IsUnique();
b.ToTable("Disciplines");
});
modelBuilder.Entity("DatabaseCore.Models.Department.DisciplineBlock", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("DisciplineBlockBlueAsteriskName")
.HasColumnType("nvarchar(max)");
b.Property<int>("DisciplineBlockOrder")
.HasColumnType("int");
b.Property<bool>("DisciplineBlockUseForGrouping")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Title")
.IsUnique();
b.ToTable("DisciplineBlocks");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Employee", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateBirth")
.HasColumnType("datetime2");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(450)");
b.Property<string>("GroupElectricalSafety")
.HasColumnType("nvarchar(max)");
b.Property<string>("HomeNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.HasColumnType("nvarchar(450)");
b.Property<string>("MobileNumber")
.HasColumnType("nvarchar(max)");
b.Property<string>("Patronymic")
.HasColumnType("nvarchar(450)");
b.Property<byte[]>("Photo")
.HasColumnType("varbinary(max)");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("FirstName", "LastName", "Patronymic")
.IsUnique()
.HasFilter("[FirstName] IS NOT NULL AND [LastName] IS NOT NULL AND [Patronymic] IS NOT NULL");
b.ToTable("Employees");
});
modelBuilder.Entity("DatabaseCore.Models.Department.EmployeeEmployeePost", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<Guid>("EmployeeId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("EmployeePostId")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsExternalCombination")
.HasColumnType("bit");
b.Property<bool>("IsInternalCombination")
.HasColumnType("bit");
b.Property<decimal>("Rate")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.HasIndex("EmployeePostId");
b.ToTable("EmployeeEmployeePosts");
});
modelBuilder.Entity("DatabaseCore.Models.Department.EmployeePost", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("EmployeePostName")
.HasColumnType("nvarchar(450)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("Order")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("EmployeePostName")
.IsUnique()
.HasFilter("[EmployeePostName] IS NOT NULL");
b.ToTable("EmployeePosts");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Lecturer", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<string>("Abbreviation")
.HasColumnType("nvarchar(max)");
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateBirth")
.HasColumnType("datetime2");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("HomeNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<Guid?>("LecturerAcademicDegreeId")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("LecturerAcademicRankId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("LecturerPostId")
.HasColumnType("uniqueidentifier");
b.Property<decimal>("LecturerPostRate")
.HasColumnType("decimal(18,2)");
b.Property<string>("MobileNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("OnlyForPrivate")
.HasColumnType("bit");
b.Property<string>("Patronymic")
.HasColumnType("nvarchar(450)");
b.Property<byte[]>("Photo")
.HasColumnType("varbinary(max)");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("LecturerAcademicDegreeId");
b.HasIndex("LecturerAcademicRankId");
b.HasIndex("LecturerPostId");
b.HasIndex("UserId");
b.HasIndex("FirstName", "LastName", "Patronymic")
.IsUnique()
.HasFilter("[Patronymic] IS NOT NULL");
b.ToTable("Lecturers");
});
modelBuilder.Entity("DatabaseCore.Models.Department.LecturerAcademicDegree", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LecturerAcademicDegreeName")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("Order")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("LecturerAcademicDegreeName")
.IsUnique();
b.ToTable("LecturerAcademicDegrees");
});
modelBuilder.Entity("DatabaseCore.Models.Department.LecturerAcademicRank", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LecturerAcademicRankName")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("Order")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("LecturerAcademicRankName")
.IsUnique();
b.ToTable("LecturerAcademicRanks");
});
modelBuilder.Entity("DatabaseCore.Models.Department.LecturerEmployeePost", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<Guid>("EmployeePostId")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsExternalCombination")
.HasColumnType("bit");
b.Property<bool>("IsInternalCombination")
.HasColumnType("bit");
b.Property<Guid>("LecturerId")
.HasColumnType("uniqueidentifier");
b.Property<decimal>("Rate")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("EmployeePostId");
b.HasIndex("LecturerId");
b.ToTable("LecturerEmployeePosts");
});
modelBuilder.Entity("DatabaseCore.Models.Department.LecturerPost", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<int>("Hours")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LecturerPostName")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("Order")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("LecturerPostName")
.IsUnique();
b.ToTable("LecturerPosts");
});
modelBuilder.Entity("DatabaseCore.Models.Security.Access", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<int>("AccessOperation")
.HasColumnType("int");
b.Property<int>("AccessType")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<Guid>("RoleId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("Accesses");
});
modelBuilder.Entity("DatabaseCore.Models.Security.EnviromentSetting", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("Key")
.IsUnique();
b.ToTable("EnviromentSettings");
});
modelBuilder.Entity("DatabaseCore.Models.Security.Role", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("RoleName")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("RolePriority")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleName")
.IsUnique();
b.ToTable("Roles");
});
modelBuilder.Entity("DatabaseCore.Models.Security.User", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<byte[]>("Avatar")
.HasColumnType("varbinary(max)");
b.Property<int>("CountAttempt")
.HasColumnType("int");
b.Property<DateTime?>("DateBanned")
.HasColumnType("datetime2");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateLastVisit")
.HasColumnType("datetime2");
b.Property<bool>("IsBanned")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserName");
b.ToTable("Users");
});
modelBuilder.Entity("DatabaseCore.Models.Security.UserRole", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<Guid>("RoleId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("UserRoles");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Classroom", b =>
{
b.HasOne("DatabaseCore.Models.Department.Employee", "Employee")
.WithMany("Classrooms")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Discipline", b =>
{
b.HasOne("DatabaseCore.Models.Department.DisciplineBlock", "DisciplineBlock")
.WithMany("Disciplines")
.HasForeignKey("DisciplineBlockId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("DisciplineBlock");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Employee", b =>
{
b.HasOne("DatabaseCore.Models.Security.User", "User")
.WithMany("Employees")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("DatabaseCore.Models.Department.EmployeeEmployeePost", b =>
{
b.HasOne("DatabaseCore.Models.Department.Employee", "Employee")
.WithMany("EmployeeEmployeePosts")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DatabaseCore.Models.Department.EmployeePost", "EmployeePost")
.WithMany("EmployeeEmployeePosts")
.HasForeignKey("EmployeePostId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
b.Navigation("EmployeePost");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Lecturer", b =>
{
b.HasOne("DatabaseCore.Models.Department.LecturerAcademicDegree", "LecturerAcademicDegree")
.WithMany("Lecturers")
.HasForeignKey("LecturerAcademicDegreeId");
b.HasOne("DatabaseCore.Models.Department.LecturerAcademicRank", "LecturerAcademicRank")
.WithMany("Lecturers")
.HasForeignKey("LecturerAcademicRankId");
b.HasOne("DatabaseCore.Models.Department.LecturerPost", "LecturerPost")
.WithMany("Lecturers")
.HasForeignKey("LecturerPostId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DatabaseCore.Models.Security.User", "User")
.WithMany("Lecturers")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("LecturerAcademicDegree");
b.Navigation("LecturerAcademicRank");
b.Navigation("LecturerPost");
b.Navigation("User");
});
modelBuilder.Entity("DatabaseCore.Models.Department.LecturerEmployeePost", b =>
{
b.HasOne("DatabaseCore.Models.Department.EmployeePost", "EmployeePost")
.WithMany("LecturerEmployeePosts")
.HasForeignKey("EmployeePostId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DatabaseCore.Models.Department.Lecturer", "Lecturer")
.WithMany("LecturerEmployeePosts")
.HasForeignKey("LecturerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("EmployeePost");
b.Navigation("Lecturer");
});
modelBuilder.Entity("DatabaseCore.Models.Security.Access", b =>
{
b.HasOne("DatabaseCore.Models.Security.Role", "Role")
.WithMany("Access")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Role");
});
modelBuilder.Entity("DatabaseCore.Models.Security.UserRole", b =>
{
b.HasOne("DatabaseCore.Models.Security.Role", "Role")
.WithMany("UserRoles")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DatabaseCore.Models.Security.User", "User")
.WithMany("UserRoles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Role");
b.Navigation("User");
});
modelBuilder.Entity("DatabaseCore.Models.Department.DisciplineBlock", b =>
{
b.Navigation("Disciplines");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Employee", b =>
{
b.Navigation("Classrooms");
b.Navigation("EmployeeEmployeePosts");
});
modelBuilder.Entity("DatabaseCore.Models.Department.EmployeePost", b =>
{
b.Navigation("EmployeeEmployeePosts");
b.Navigation("LecturerEmployeePosts");
});
modelBuilder.Entity("DatabaseCore.Models.Department.Lecturer", b =>
{
b.Navigation("LecturerEmployeePosts");
});
modelBuilder.Entity("DatabaseCore.Models.Department.LecturerAcademicDegree", b =>
{
b.Navigation("Lecturers");
});
modelBuilder.Entity("DatabaseCore.Models.Department.LecturerAcademicRank", b =>
{
b.Navigation("Lecturers");
});
modelBuilder.Entity("DatabaseCore.Models.Department.LecturerPost", b =>
{
b.Navigation("Lecturers");
});
modelBuilder.Entity("DatabaseCore.Models.Security.Role", b =>
{
b.Navigation("Access");
b.Navigation("UserRoles");
});
modelBuilder.Entity("DatabaseCore.Models.Security.User", b =>
{
b.Navigation("Employees");
b.Navigation("Lecturers");
b.Navigation("UserRoles");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace DatabaseCore.Migrations
{
public partial class AddEnviromentSettingsFields : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "DateCreate",
table: "EnviromentSettings",
type: "datetime2",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
migrationBuilder.AddColumn<DateTime>(
name: "DateDelete",
table: "EnviromentSettings",
type: "datetime2",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "EnviromentSettings",
type: "bit",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DateCreate",
table: "EnviromentSettings");
migrationBuilder.DropColumn(
name: "DateDelete",
table: "EnviromentSettings");
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "EnviromentSettings");
}
}
}

View File

@ -530,9 +530,18 @@ namespace DatabaseCore.Migrations
b.Property<Guid>("Id") b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier"); .HasColumnType("uniqueidentifier");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateDelete")
.HasColumnType("datetime2");
b.Property<string>("Description") b.Property<string>("Description")
.HasColumnType("nvarchar(max)"); .HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Key") b.Property<string>("Key")
.IsRequired() .IsRequired()
.HasColumnType("nvarchar(450)"); .HasColumnType("nvarchar(450)");

View File

@ -10,7 +10,7 @@ namespace DatabaseCore.Models.Security
/// </summary> /// </summary>
[DataContract] [DataContract]
[EntityDescription("EnviromentSetting", "Общие настройки системы")] [EntityDescription("EnviromentSetting", "Общие настройки системы")]
public class EnviromentSetting : IdEntity, IEntitySecurityExtenstion<EnviromentSetting> public class EnviromentSetting : BaseEntity, IEntitySecurityExtenstion<EnviromentSetting>
{ {
[DataMember] [DataMember]
[Required] [Required]

View File

@ -1,4 +1,7 @@
using ModuleTools.Interfaces; using ModuleTools.BindingModels;
using ModuleTools.Enums;
using ModuleTools.Interfaces;
using ModuleTools.Models;
using System.Collections.Generic; using System.Collections.Generic;
namespace ModuleTools.BusinessLogics namespace ModuleTools.BusinessLogics
@ -13,6 +16,16 @@ namespace ModuleTools.BusinessLogics
/// </summary> /// </summary>
protected readonly ISecurityManager _security; protected readonly ISecurityManager _security;
/// <summary>
/// Тип операции, скоторым работает логика
/// </summary>
protected AccessOperation _serviceOperation;
/// <summary>
/// Название сущности
/// </summary>
protected string _entity;
/// <summary> /// <summary>
/// Перечень ошибок при выполнении операции /// Перечень ошибок при выполнении операции
/// </summary> /// </summary>
@ -27,5 +40,21 @@ namespace ModuleTools.BusinessLogics
_security = DependencyManager.Instance.Resolve<ISecurityManager>(); _security = DependencyManager.Instance.Resolve<ISecurityManager>();
Errors = new(); Errors = new();
} }
/// <summary>
/// Проверка доступности операции для пользователя
/// </summary>
/// <param name="model"></param>
/// <param name="type"></param>
/// <returns></returns>
protected bool NoAccess(AccessBindingModel model, AccessType type)
{
if (_security.CheckAccess(new SecurityManagerCheckAccessModel(model, _serviceOperation, type, _entity)))
{
return false;
}
Errors.Add(("Ошибка безопасности", _security.ErrorMessage));
return true;
}
} }
} }

View File

@ -1,7 +1,6 @@
using ModuleTools.BindingModels; using ModuleTools.BindingModels;
using ModuleTools.Enums; using ModuleTools.Enums;
using ModuleTools.Interfaces; using ModuleTools.Interfaces;
using ModuleTools.Models;
using ModuleTools.ViewModels; using ModuleTools.ViewModels;
using System; using System;
@ -25,16 +24,6 @@ namespace ModuleTools.BusinessLogics
/// </summary> /// </summary>
protected IGenerticEntityService<G, S> Service { get; set; } protected IGenerticEntityService<G, S> Service { get; set; }
/// <summary>
/// Тип операции, скоторым работает логика
/// </summary>
protected readonly AccessOperation _serviceOperation;
/// <summary>
/// Название сущности
/// </summary>
protected readonly string _entity;
/// <summary> /// <summary>
/// Возможен ли просмотр без авторизации /// Возможен ли просмотр без авторизации
/// </summary> /// </summary>
@ -47,22 +36,6 @@ namespace ModuleTools.BusinessLogics
_serviceOperation = serviceOperation; _serviceOperation = serviceOperation;
} }
/// <summary>
/// Проверка доступности операции для пользователя
/// </summary>
/// <param name="model"></param>
/// <param name="type"></param>
/// <returns></returns>
protected bool NoAccess(AccessBindingModel model, AccessType type)
{
if (_security.CheckAccess(new SecurityManagerCheckAccessModel(model, _serviceOperation, type, _entity)))
{
return false;
}
Errors.Add(("Ошибка безопасности", _security.ErrorMessage));
return true;
}
/// <summary> /// <summary>
/// Получение списка записей /// Получение списка записей
/// </summary> /// </summary>

View File

@ -1,7 +1,6 @@
using ModuleTools.BusinessLogics; using ModuleTools.BusinessLogics;
using ModuleTools.Enums; using ModuleTools.Enums;
using ModuleTools.Extensions; using ModuleTools.Extensions;
using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.Interfaces;
using System; using System;
@ -23,7 +22,12 @@ namespace SecurityBusinessLogic.BusinessLogics
/// Логика работы с бекапом /// Логика работы с бекапом
/// </summary> /// </summary>
/// <param name="service"></param> /// <param name="service"></param>
public BackupBusinessLogic(IBackupService service) => _service = service; public BackupBusinessLogic(IBackupService service)
{
_service = service;
_serviceOperation = AccessOperation.РаботасБекапом;
_entity = "Работа с Бекапом";
}
/// <summary> /// <summary>
/// Создание бекапа с данными /// Создание бекапа с данными
@ -39,7 +43,7 @@ namespace SecurityBusinessLogic.BusinessLogics
} }
try try
{ {
if (NoAccess()) if (NoAccess(null, AccessType.Delete))
{ {
return false; return false;
} }
@ -82,7 +86,7 @@ namespace SecurityBusinessLogic.BusinessLogics
} }
try try
{ {
if (NoAccess()) if (NoAccess(null, AccessType.Delete))
{ {
return false; return false;
} }
@ -100,19 +104,5 @@ namespace SecurityBusinessLogic.BusinessLogics
return false; return false;
} }
} }
/// <summary>
/// Проверка доступности операции для пользователя
/// </summary>
/// <returns></returns>
private bool NoAccess()
{
if (_security.CheckAccess(new SecurityManagerCheckAccessModel(null, AccessOperation.РаботасБекапом, AccessType.Delete, "бекап")))
{
return false;
}
Errors.Add(("Ошибка безопасности", _security.ErrorMessage));
return true;
}
} }
} }

View File

@ -1,6 +1,5 @@
using ModuleTools.BusinessLogics; using ModuleTools.BusinessLogics;
using ModuleTools.Enums; using ModuleTools.Enums;
using ModuleTools.Models;
using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.Interfaces;
using System; using System;
@ -20,7 +19,12 @@ namespace SecurityBusinessLogic.BusinessLogics
/// Логика работы с бекапом /// Логика работы с бекапом
/// </summary> /// </summary>
/// <param name="service"></param> /// <param name="service"></param>
public SynchronizationBusinessLogic(ISynchronizationService service) => _service = service; public SynchronizationBusinessLogic(ISynchronizationService service)
{
_service = service;
_serviceOperation = AccessOperation.Синхронизация;
_entity = "Синхронизация";
}
/// <summary> /// <summary>
/// Запуск синхронизации /// Запуск синхронизации
@ -31,7 +35,7 @@ namespace SecurityBusinessLogic.BusinessLogics
{ {
try try
{ {
if (NoAccess()) if (NoAccess(null, AccessType.Delete))
{ {
return false; return false;
} }
@ -49,19 +53,5 @@ namespace SecurityBusinessLogic.BusinessLogics
return false; return false;
} }
} }
/// <summary>
/// Проверка доступности операции для пользователя
/// </summary>
/// <returns></returns>
private bool NoAccess()
{
if (_security.CheckAccess(new SecurityManagerCheckAccessModel(null, AccessOperation.Синхронизация, AccessType.Delete, "Синхронизация")))
{
return false;
}
Errors.Add(("Ошибка безопасности", _security.ErrorMessage));
return true;
}
} }
} }

View File

@ -1,14 +1,10 @@
using DatabaseCore; using DatabaseCore;
using DatabaseCore.Models.Security; using DatabaseCore.Models.Security;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using ModuleTools.Extensions;
using ModuleTools.Models; using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.Interfaces;
using SecurityBusinessLogic.ViewModels; using SecurityBusinessLogic.ViewModels;
using System;
using System.Linq; using System.Linq;
namespace SecurityDatabaseImplementation.Implementations namespace SecurityDatabaseImplementation.Implementations
@ -16,118 +12,33 @@ namespace SecurityDatabaseImplementation.Implementations
/// <summary> /// <summary>
/// Реализация IAccessService /// Реализация IAccessService
/// </summary> /// </summary>
public class AccessService : IAccessService public class AccessService :
AbstractGenerticEntityService<AccessGetBindingModel, AccessSetBindingModel, Access, AccessListViewModel, AccessViewModel>,
IAccessService
{ {
public OperationResultModel Create(AccessSetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, AccessSetBindingModel model) => OperationResultModel.Success(null);
protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, AccessGetBindingModel model) { return OperationResultModel.Success(null); }
protected override IQueryable<Access> AdditionalCheckingWhenReadingList(IQueryable<Access> query, AccessGetBindingModel model)
{ {
using var context = DatabaseManager.GetContext;
var exsistEntity = context.Accesses.FirstOrDefault(x => x.AccessOperation == model.AccessOperation && x.RoleId == model.RoleId && x.AccessType == model.AccessType);
if (exsistEntity == null)
{
var entity = Mapper.MapToClass<AccessSetBindingModel, Access>(model, true);
context.Accesses.Add(entity);
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<Access, AccessViewModel>(entity, true));
}
else
{
if (exsistEntity.IsDeleted)
{
exsistEntity = Mapper.MapToClass(model, exsistEntity, true);
exsistEntity.IsDeleted = false;
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<Access, AccessViewModel>(exsistEntity, true));
}
else
{
return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem);
}
}
}
public OperationResultModel Delete(AccessGetBindingModel model)
{
using var context = DatabaseManager.GetContext;
var entity = context.Accesses.FirstOrDefault(x => x.Id == model.Id);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
entity.IsDeleted = true;
entity.DateDelete = DateTime.Now;
context.SaveChanges();
return OperationResultModel.Success(true);
}
public OperationResultModel Read(AccessGetBindingModel model)
{
int countPages = 0;
using var context = DatabaseManager.GetContext;
// для одной записи
if(model.Id.HasValue)
{
var entity = context.Accesses.FirstOrDefault(x => x.Id == model.Id.Value);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
return OperationResultModel.Success(Mapper.MapToClass<Access, AccessViewModel>(entity, model.HaveRight));
}
var query = context.Accesses.Where(x => !x.IsDeleted).AsQueryable();
if (model.RoleId.HasValue) if (model.RoleId.HasValue)
{ {
query = query.Where(x => x.RoleId == model.RoleId); query = query.Where(x => x.RoleId == model.RoleId);
} }
return query;
query = query.OrderBy(x => x.Role.RoleName).ThenBy(x => x.AccessOperation).ThenBy(x => x.AccessType);
if (model.PageNumber.HasValue && model.PageSize.HasValue)
{
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
query = query
.Skip(model.PageSize.Value * model.PageNumber.Value)
.Take(model.PageSize.Value);
}
query = query.Include(x => x.Role);
var result = new AccessListViewModel
{
MaxCount = countPages,
List = query.Select(x => Mapper.MapToClass<Access, AccessViewModel>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result);
} }
public OperationResultModel Update(AccessSetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, AccessSetBindingModel model) => OperationResultModel.Success(null);
{
using var context = DatabaseManager.GetContext;
var entity = context.Accesses.FirstOrDefault(x => x.Id == model.Id); protected override void AdditionalDeleting(DbContext context, AccessGetBindingModel model) { }
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
entity = Mapper.MapToClass(model, entity, true);
context.SaveChanges(); protected override Access GetUniqueEntity(AccessSetBindingModel model, DbContext context) =>
context.Set<Access>().FirstOrDefault(x => x.AccessOperation == model.AccessOperation && x.RoleId == model.RoleId && x.AccessType == model.AccessType && x.Id != model.Id);
return OperationResultModel.Success(Mapper.MapToClass<Access, AccessViewModel>(entity, true)); protected override IQueryable<Access> IncludingWhenReading(IQueryable<Access> query) => query.Include(x => x.Role);
}
protected override IQueryable<Access> OrderingWhenReading(IQueryable<Access> query) =>
query.OrderBy(x => x.Role.RoleName).ThenBy(x => x.AccessOperation).ThenBy(x => x.AccessType);
} }
} }

View File

@ -1,13 +1,10 @@
using DatabaseCore; using DatabaseCore;
using DatabaseCore.Models.Security; using DatabaseCore.Models.Security;
using ModuleTools.BusinessLogics; using Microsoft.EntityFrameworkCore;
using ModuleTools.Enums;
using ModuleTools.Extensions;
using ModuleTools.Models; using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.Interfaces;
using SecurityBusinessLogic.ViewModels; using SecurityBusinessLogic.ViewModels;
using System;
using System.Linq; using System.Linq;
namespace SecurityDatabaseImplementation.Implementations namespace SecurityDatabaseImplementation.Implementations
@ -15,100 +12,24 @@ namespace SecurityDatabaseImplementation.Implementations
/// <summary> /// <summary>
/// Реализация IEnviromentSettingService /// Реализация IEnviromentSettingService
/// </summary> /// </summary>
public class EnviromentSettingService : IEnviromentSettingService public class EnviromentSettingService :
AbstractGenerticEntityService<EnviromentSettingGetBindingModel, EnviromentSettingSetBindingModel, EnviromentSetting, EnviromentSettingListViewModel, EnviromentSettingViewModel>,
IEnviromentSettingService
{ {
public OperationResultModel Create(EnviromentSettingSetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, EnviromentSettingSetBindingModel model) => OperationResultModel.Success(null);
{
using var context = DatabaseManager.GetContext;
var exsistEntity = context.EnviromentSettings.FirstOrDefault(x => x.Key == model.Key); protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, EnviromentSettingGetBindingModel model) => OperationResultModel.Success(null);
if (exsistEntity == null)
{
var entity = Mapper.MapToClass<EnviromentSettingSetBindingModel, EnviromentSetting>(model, true);
context.EnviromentSettings.Add(entity);
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<EnviromentSetting, EnviromentSettingViewModel>(entity, true));
}
return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem);
}
public OperationResultModel Delete(EnviromentSettingGetBindingModel model) protected override IQueryable<EnviromentSetting> AdditionalCheckingWhenReadingList(IQueryable<EnviromentSetting> query, EnviromentSettingGetBindingModel model) => query;
{
using var context = DatabaseManager.GetContext;
var entity = context.EnviromentSettings.FirstOrDefault(x => x.Id == model.Id); protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, EnviromentSettingSetBindingModel model) => OperationResultModel.Success(null);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
context.EnviromentSettings.Remove(entity); protected override void AdditionalDeleting(DbContext context, EnviromentSettingGetBindingModel model) { }
context.SaveChanges();
return OperationResultModel.Success(true); protected override EnviromentSetting GetUniqueEntity(EnviromentSettingSetBindingModel model, DbContext context) => context.Set<EnviromentSetting>().FirstOrDefault(x => x.Key == model.Key && x.Id != model.Id);
}
public OperationResultModel Read(EnviromentSettingGetBindingModel model) protected override IQueryable<EnviromentSetting> IncludingWhenReading(IQueryable<EnviromentSetting> query) => query;
{
int countPages = 0;
using var context = DatabaseManager.GetContext;
// для одной записи protected override IQueryable<EnviromentSetting> OrderingWhenReading(IQueryable<EnviromentSetting> query) => query.OrderBy(x => x.Key);
if (model.Id.HasValue)
{
var entity = context.EnviromentSettings.FirstOrDefault(x => x.Id == model.Id.Value);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
return OperationResultModel.Success(Mapper.MapToClass<EnviromentSetting, EnviromentSettingViewModel>(entity, model.HaveRight));
}
if (model.Key.IsNotEmpty())
{
var entity = context.EnviromentSettings.FirstOrDefault(x => x.Key == model.Key);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
return OperationResultModel.Success(Mapper.MapToClass<EnviromentSetting, EnviromentSettingViewModel>(entity, model.HaveRight));
}
var query = context.EnviromentSettings.AsQueryable();
query = query.OrderBy(x => x.Key);
if (model.PageNumber.HasValue && model.PageSize.HasValue)
{
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
query = query
.Skip(model.PageSize.Value * model.PageNumber.Value)
.Take(model.PageSize.Value);
}
var result = new EnviromentSettingListViewModel
{
MaxCount = countPages,
List = query.Select(x => Mapper.MapToClass<EnviromentSetting, EnviromentSettingViewModel>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result);
}
public OperationResultModel Update(EnviromentSettingSetBindingModel model)
{
using var context = DatabaseManager.GetContext;
var entity = context.EnviromentSettings.FirstOrDefault(x => x.Id == model.Id);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
entity = Mapper.MapToClass(model, entity, true);
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<EnviromentSetting, EnviromentSettingViewModel>(entity, true));
}
} }
} }

View File

@ -1,6 +1,6 @@
using DatabaseCore; using DatabaseCore;
using DatabaseCore.Models.Security; using DatabaseCore.Models.Security;
using ModuleTools.BusinessLogics; using Microsoft.EntityFrameworkCore;
using ModuleTools.Enums; using ModuleTools.Enums;
using ModuleTools.Models; using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BindingModels;
@ -14,135 +14,40 @@ namespace SecurityDatabaseImplementation.Implementations
/// <summary> /// <summary>
/// Реализация IRoleService /// Реализация IRoleService
/// </summary> /// </summary>
public class RoleService : IRoleService public class RoleService :
AbstractGenerticEntityService<RoleGetBindingModel, RoleSetBindingModel, Role, RoleListViewModel, RoleViewModel>,
IRoleService
{ {
public OperationResultModel Create(RoleSetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, RoleSetBindingModel model) => OperationResultModel.Success(null);
{
using var context = DatabaseManager.GetContext;
var exsistEntity = context.Roles.FirstOrDefault(x => x.RoleName == model.RoleName); protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, RoleGetBindingModel model)
if (exsistEntity == null) {
if (context.Set<UserRole>().Any(x => x.RoleId == model.Id && !x.IsDeleted))
{ {
var entity = Mapper.MapToClass<RoleSetBindingModel, Role>(model, true); return OperationResultModel.Error("Error:", "Существуют пользователи, у которых есть эта роль", ResultServiceStatusCode.ExsistItem);
context.Roles.Add(entity);
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<Role, RoleViewModel>(entity, true));
}
else
{
if (exsistEntity.IsDeleted)
{
exsistEntity = Mapper.MapToClass(model, exsistEntity, true);
exsistEntity.IsDeleted = false;
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<Role, RoleViewModel>(exsistEntity, true));
}
else
{
return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem);
}
} }
return OperationResultModel.Success(null);
} }
public OperationResultModel Delete(RoleGetBindingModel model) protected override IQueryable<Role> AdditionalCheckingWhenReadingList(IQueryable<Role> query, RoleGetBindingModel model) => query;
protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, RoleSetBindingModel model) => OperationResultModel.Success(null);
protected override void AdditionalDeleting(DbContext context, RoleGetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; var access = context.Set<Access>().Where(x => x.RoleId == model.Id);
using var transaction = context.Database.BeginTransaction(); foreach (var ac in access)
try
{ {
var entity = context.Roles.FirstOrDefault(x => x.Id == model.Id); ac.IsDeleted = true;
if (entity == null) ac.DateDelete = DateTime.Now;
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
if(context.UserRoles.Any(x => x.RoleId == model.Id && !x.IsDeleted))
{
return OperationResultModel.Error("Error:", "Существуют пользователи, у которых есть эта роль", ResultServiceStatusCode.ExsistItem);
}
entity.IsDeleted = true;
entity.DateDelete = DateTime.Now;
context.SaveChanges();
var access = context.Accesses.Where(x => x.RoleId == model.Id);
foreach(var ac in access)
{
ac.IsDeleted = true;
ac.DateDelete = DateTime.Now;
}
context.SaveChanges();
transaction.Commit();
} }
catch(Exception)
{
transaction.Rollback();
throw;
}
return OperationResultModel.Success(true);
}
public OperationResultModel Read(RoleGetBindingModel model)
{
int countPages = 0;
using var context = DatabaseManager.GetContext;
// для одной записи
if (model.Id.HasValue)
{
var entity = context.Roles.FirstOrDefault(x => x.Id == model.Id.Value);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
return OperationResultModel.Success(Mapper.MapToClass<Role, RoleViewModel>(entity, model.HaveRight));
}
var query = context.Roles.Where(x => !x.IsDeleted).AsQueryable();
query = query.OrderBy(x => x.RoleName);
if (model.PageNumber.HasValue && model.PageSize.HasValue)
{
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
query = query
.Skip(model.PageSize.Value * model.PageNumber.Value)
.Take(model.PageSize.Value);
}
var result = new RoleListViewModel
{
MaxCount = countPages,
List = query.Select(x => Mapper.MapToClass<Role, RoleViewModel>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result);
}
public OperationResultModel Update(RoleSetBindingModel model)
{
using var context = DatabaseManager.GetContext;
var entity = context.Roles.FirstOrDefault(x => x.Id == model.Id);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
entity = Mapper.MapToClass<RoleSetBindingModel, Role>(model, entity, true);
context.SaveChanges(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<Role, RoleViewModel>(entity, true));
} }
protected override Role GetUniqueEntity(RoleSetBindingModel model, DbContext context) => context.Set<Role>().FirstOrDefault(x => x.RoleName == model.RoleName && x.Id != model.Id);
protected override IQueryable<Role> IncludingWhenReading(IQueryable<Role> query) => query;
protected override IQueryable<Role> OrderingWhenReading(IQueryable<Role> query) => query.OrderBy(x => x.RoleName);
} }
} }

View File

@ -1,13 +1,10 @@
using DatabaseCore; using DatabaseCore;
using DatabaseCore.Models.Security; using DatabaseCore.Models.Security;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using ModuleTools.Models; using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.Interfaces;
using SecurityBusinessLogic.ViewModels; using SecurityBusinessLogic.ViewModels;
using System;
using System.Linq; using System.Linq;
namespace SecurityDatabaseImplementation.Implementations namespace SecurityDatabaseImplementation.Implementations
@ -15,74 +12,16 @@ namespace SecurityDatabaseImplementation.Implementations
/// <summary> /// <summary>
/// Реализация IUserRoleService /// Реализация IUserRoleService
/// </summary> /// </summary>
public class UserRoleService : IUserRoleService public class UserRoleService :
AbstractGenerticEntityService<UserRoleGetBindingModel, UserRoleSetBindingModel, UserRole, UserRoleListViewModel, UserRoleViewModel>,
IUserRoleService
{ {
public OperationResultModel Create(UserRoleSetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, UserRoleSetBindingModel model) => OperationResultModel.Success(null);
protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, UserRoleGetBindingModel model) => OperationResultModel.Success(null);
protected override IQueryable<UserRole> AdditionalCheckingWhenReadingList(IQueryable<UserRole> query, UserRoleGetBindingModel model)
{ {
using var context = DatabaseManager.GetContext;
var exsistEntity = context.UserRoles.FirstOrDefault(x => x.UserId == model.UserId && x.RoleId == model.RoleId);
if (exsistEntity == null)
{
var entity = Mapper.MapToClass<UserRoleSetBindingModel, UserRole>(model, true);
context.UserRoles.Add(entity);
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<UserRole, UserRoleViewModel>(entity, true));
}
else
{
if (exsistEntity.IsDeleted)
{
exsistEntity = Mapper.MapToClass(model, exsistEntity, true);
exsistEntity.IsDeleted = false;
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<UserRole, UserRoleViewModel>(exsistEntity, true));
}
else
{
return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem);
}
}
}
public OperationResultModel Delete(UserRoleGetBindingModel model)
{
using var context = DatabaseManager.GetContext;
var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
entity.IsDeleted = true;
entity.DateDelete = DateTime.Now;
context.SaveChanges();
return OperationResultModel.Success(true);
}
public OperationResultModel Read(UserRoleGetBindingModel model)
{
int countPages = 0;
using var context = DatabaseManager.GetContext;
// для одной записи
if (model.Id.HasValue)
{
var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id.Value);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
return OperationResultModel.Success(Mapper.MapToClass<UserRole, UserRoleViewModel>(entity, model.HaveRight));
}
var query = context.UserRoles.Where(x => !x.IsDeleted).AsQueryable();
if (model.RoleId.HasValue) if (model.RoleId.HasValue)
{ {
query = query.Where(x => x.RoleId == model.RoleId); query = query.Where(x => x.RoleId == model.RoleId);
@ -91,46 +30,17 @@ namespace SecurityDatabaseImplementation.Implementations
{ {
query = query.Where(x => x.UserId == model.UserId); query = query.Where(x => x.UserId == model.UserId);
} }
return query;
query = query.OrderBy(x => x.User.UserName);
if (model.PageNumber.HasValue && model.PageSize.HasValue)
{
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
query = query
.Skip(model.PageSize.Value * model.PageNumber.Value)
.Take(model.PageSize.Value);
}
query = query.Include(x => x.Role).Include(x => x.User);
var result = new UserRoleListViewModel
{
MaxCount = countPages,
List = query.Select(x => Mapper.MapToClass<UserRole, UserRoleViewModel>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result);
} }
public OperationResultModel Update(UserRoleSetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, UserRoleSetBindingModel model) => OperationResultModel.Success(null);
{
using var context = DatabaseManager.GetContext;
var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id); protected override void AdditionalDeleting(DbContext context, UserRoleGetBindingModel model) { }
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
entity = Mapper.MapToClass(model, entity, true);
context.SaveChanges(); protected override UserRole GetUniqueEntity(UserRoleSetBindingModel model, DbContext context) => context.Set<UserRole>().FirstOrDefault(x => x.UserId == model.UserId && x.RoleId == model.RoleId && x.Id != model.Id);
return OperationResultModel.Success(Mapper.MapToClass<UserRole, UserRoleViewModel>(entity, true)); protected override IQueryable<UserRole> IncludingWhenReading(IQueryable<UserRole> query) => query.Include(x => x.Role).Include(x => x.User);
}
protected override IQueryable<UserRole> OrderingWhenReading(IQueryable<UserRole> query) => query.OrderBy(x => x.User.UserName);
} }
} }

View File

@ -1,6 +1,7 @@
using DatabaseCore; using DatabaseCore;
using DatabaseCore.Models.Department;
using DatabaseCore.Models.Security; using DatabaseCore.Models.Security;
using ModuleTools.BusinessLogics; using Microsoft.EntityFrameworkCore;
using ModuleTools.Enums; using ModuleTools.Enums;
using ModuleTools.Extensions; using ModuleTools.Extensions;
using ModuleTools.Models; using ModuleTools.Models;
@ -15,156 +16,59 @@ namespace SecurityDatabaseImplementation.Implementations
/// <summary> /// <summary>
/// Реализация IUserService /// Реализация IUserService
/// </summary> /// </summary>
public class UserService : IUserService public class UserService :
AbstractGenerticEntityService<UserGetBindingModel, UserSetBindingModel, User, UserListViewModel, UserViewModel>,
IUserService
{ {
public OperationResultModel Create(UserSetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, UserSetBindingModel model)
{ {
using var context = DatabaseManager.GetContext;
if (model.Password.IsEmpty()) if (model.Password.IsEmpty())
{ {
model.Password = "qwerty"; model.Password = "qwerty";
} }
model.Password = SecurityManager.GetPasswordHash(model.Password); model.Password = SecurityManager.GetPasswordHash(model.Password);
return OperationResultModel.Success(null);
var exsistEntity = context.Users.FirstOrDefault(x => x.UserName == model.Login);
if (exsistEntity == null)
{
var entity = Mapper.MapToClass<UserSetBindingModel, User>(model, true);
context.Users.Add(entity);
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<User, UserViewModel>(entity, true));
}
else
{
if (exsistEntity.IsDeleted)
{
exsistEntity = Mapper.MapToClass(model, exsistEntity, true);
exsistEntity.IsDeleted = false;
context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<User, UserViewModel>(exsistEntity, true));
}
else
{
return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem);
}
}
} }
public OperationResultModel Delete(UserGetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, UserGetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; if (context.Set<Employee>().Any(x => x.UserId == model.Id && !x.IsDeleted))
using var transaction = context.Database.BeginTransaction();
try
{ {
var entity = context.Users.FirstOrDefault(x => x.Id == model.Id); return OperationResultModel.Error("Error:", "Имеется сотрудник, приязанный к этой учетке", ResultServiceStatusCode.ExsistItem);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
if (context.Employees.Any(x => x.UserId == model.Id && !x.IsDeleted))
{
return OperationResultModel.Error("Error:", "Имеется сотрудник, приязанный к этой учетке", ResultServiceStatusCode.ExsistItem);
}
if (context.Lecturers.Any(x => x.UserId == model.Id && !x.IsDeleted))
{
return OperationResultModel.Error("Error:", "Имеется преподаватель, приязанный к этой учетке", ResultServiceStatusCode.ExsistItem);
}
entity.IsDeleted = true;
entity.DateDelete = DateTime.Now;
context.SaveChanges();
var users = context.UserRoles.Where(x => x.UserId == model.Id);
foreach (var u in users)
{
u.IsDeleted = true;
u.DateDelete = DateTime.Now;
}
context.SaveChanges();
transaction.Commit();
} }
catch (Exception) if (context.Set<Lecturer>().Any(x => x.UserId == model.Id && !x.IsDeleted))
{ {
transaction.Rollback(); return OperationResultModel.Error("Error:", "Имеется преподаватель, приязанный к этой учетке", ResultServiceStatusCode.ExsistItem);
throw;
} }
return OperationResultModel.Success(null);
return OperationResultModel.Success(true);
} }
public OperationResultModel Read(UserGetBindingModel model) protected override IQueryable<User> AdditionalCheckingWhenReadingList(IQueryable<User> query, UserGetBindingModel model)
{ {
int countPages = 0; if (model.UserNameForSearch.IsNotEmpty())
using var context = DatabaseManager.GetContext;
// для одной записи
if (model.Id.HasValue)
{
var entity = context.Users.FirstOrDefault(x => x.Id == model.Id.Value);
if (entity == null)
{
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
}
return OperationResultModel.Success(Mapper.MapToClass<User, UserViewModel>(entity, model.HaveRight));
}
var query = context.Users.Where(x => !x.IsDeleted).AsQueryable();
if(model.UserNameForSearch.IsNotEmpty())
{ {
query = query.Where(x => x.UserName.Contains(model.UserNameForSearch)); query = query.Where(x => x.UserName.Contains(model.UserNameForSearch));
} }
return query;
query = query.OrderBy(x => x.UserName);
if (model.PageNumber.HasValue && model.PageSize.HasValue)
{
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
query = query
.Skip(model.PageSize.Value * model.PageNumber.Value)
.Take(model.PageSize.Value);
}
var result = new UserListViewModel
{
MaxCount = countPages,
List = query.Select(x => Mapper.MapToClass<User, UserViewModel>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result);
} }
public OperationResultModel Update(UserSetBindingModel model) protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, UserSetBindingModel model) => OperationResultModel.Success(null);
protected override void AdditionalDeleting(DbContext context, UserGetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; var users = context.Set<UserRole>().Where(x => x.UserId == model.Id);
foreach (var u in users)
var entity = context.Users.FirstOrDefault(x => x.Id == model.Id);
if (entity == null)
{ {
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); u.IsDeleted = true;
u.DateDelete = DateTime.Now;
} }
else if (entity.IsDeleted)
{
return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete);
}
if(entity.IsBanned && !model.IsBanned)
{
model.DateBanned = null;
model.CountAttempt = 0;
}
entity = Mapper.MapToClass(model, entity, true);
context.SaveChanges(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<User, UserViewModel>(entity, true));
} }
protected override User GetUniqueEntity(UserSetBindingModel model, DbContext context) => context.Set<User>().FirstOrDefault(x => x.UserName == model.Login && x.Id != model.Id);
protected override IQueryable<User> IncludingWhenReading(IQueryable<User> query) => query;
protected override IQueryable<User> OrderingWhenReading(IQueryable<User> query) => query.OrderBy(x => x.UserName);
} }
} }