using UniversityContracts.BindingModels; using UniversityContracts.SearchModels; using UniversityContracts.StoragesContracts; using UniversityContracts.ViewModels; using UniversityDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; namespace UniversityDatabaseImplement.Implements { public class RequirementStorage : IRequirementStorage { private void CheckSearchModel(RequirementSearchModel model) { if (model == null) throw new ArgumentNullException("Передаваемая модель для поиска равна нулю", nameof(model)); if (!model.Id.HasValue && !model.DirectorId.HasValue) throw new ArgumentException("Все передаваемые поля поисковой модели оказались пусты или равны null"); } public RequirementViewModel? Delete(RequirementBindingModel model) { using var context = new UniversityDB(); var element = context.Requirements.FirstOrDefault(x => x.Id == model.Id); if (element != null) { context.Requirements.Remove(element); context.SaveChanges(); return element; } return null; } public RequirementViewModel? GetElement(RequirementSearchModel model) { CheckSearchModel(model); using var context = new UniversityDB(); if (!model.Id.HasValue) { return null; } return context.Requirements .Include(requirement => requirement.Director) .Include(requirement => requirement.Disciplines).ThenInclude(requirementByDiscipline => requirementByDiscipline.Discipline) .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id); } public List GetFilteredList(RequirementSearchModel model) { CheckSearchModel(model); using var context = new UniversityDB(); return context.Requirements .Include(requirement => requirement.Director) .Include(requirement => requirement.Disciplines).ThenInclude(requirementByDiscipline => requirementByDiscipline.Discipline) .Where(x => x.DirectorId == model.DirectorId) .Select(x => (RequirementViewModel)x) .ToList(); } public List GetFullList() { using var context = new UniversityDB(); return context.Requirements .Include(requirement => requirement.Director) .Include(requirement => requirement.Disciplines).ThenInclude(requirementByDiscipline => requirementByDiscipline.Discipline) .Select(x => (RequirementViewModel)x) .ToList(); } public RequirementViewModel? Insert(RequirementBindingModel model) { var newRequirement = Requirement.Create(model); if (newRequirement == null) { return null; } using var context = new UniversityDB(); // Согласно тз при создании требований не требуется связывать ее с дисциплиными, поэтому нет UpdateDisciplines context.Requirements.Add(newRequirement); context.SaveChanges(); return newRequirement; } public RequirementViewModel? Update(RequirementBindingModel model) { using var context = new UniversityDB(); var requirement = context.Requirements.FirstOrDefault(x => x.Id == model.Id); if (requirement == null) { return null; } requirement.Update(model); context.SaveChanges(); requirement.UpdateDisciplines(context, model); context.SaveChanges(); return requirement; } } }