using SchoolContracts.BindingModels; using SchoolContracts.Extensions; using SchoolContracts.ViewModels; using SchoolDataModels; using System.ComponentModel.DataAnnotations; using SchoolDataModels.Models; namespace SchoolDatabaseImplement.Models { public class Requirement : IRequirementModel { [Required] public int ExecutorId { get; private set; } [Required] public string NameOfRequirement { get; private set; } = string.Empty; public int Id { get; private set; } [Required] public double Price { get; private set; } private Dictionary? _cachedDisciplines; public Dictionary DisciplinesModels => _cachedDisciplines ??= Disciplines.Select(x => (RequirementByDisciplineModel)x).ToDictionary(x => x.DisciplineId, x => x); [Required] public Executor? Executor { get; private set; } [Required] public List Disciplines { get; private set; } = new(); public static Requirement Create(RequirementBindingModel model) => model.CastWithCommonProperties(); public static implicit operator RequirementViewModel(Requirement? model) { if (model == null) { throw new ArgumentNullException("Возникла ошибка при попытки получить View-модель из null-объекта", nameof(model)); } model._cachedDisciplines = null; var result = model.CastWithCommonProperties(); result.ExecutorLogin = model.Executor?.Login ?? string.Empty; return result; } public void Update(RequirementBindingModel model) { Price = model.Price; } /// /// Привязка требований к дисциплиным /// public void UpdateDisciplines(SchoolDB context, RequirementBindingModel model) { var oldDisciplines = context.RequirementByDisciplines.Where(x => x.DisciplineId == model.Id).ToDictionary(x => x.DisciplineId, x => x); var newDisciplines = model.DisciplinesModels.ToDictionary( x => x.Key, x => { var res = x.Value.CastWithCommonProperties(); res.RequirementId = model.Id; res.DisciplineId = x.Key; return res; }); context.RemoveRange(oldDisciplines.Where(x => !newDisciplines.ContainsKey(x.Key)).Select(x => x.Value)); context.SaveChanges(); context.AddRange (newDisciplines.Where(x => !oldDisciplines.ContainsKey(x.Key)).Select(x => x.Value)); oldDisciplines.Where(x => newDisciplines.ContainsKey(x.Key)) .Select(x => x.Value).ToList() .ForEach(x => x.Count = newDisciplines[x.DisciplineId].Count); context.SaveChanges(); _cachedDisciplines = null; } } }