using SchoolContracts.BindingModels; using SchoolContracts.Extensions; using SchoolContracts.ViewModels; using SchoolDataModels; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq.Expressions; using SchoolDataModels.Models; namespace SchoolDatabaseImplement.Models { public class Discipline : IDisciplineModel { public int ImplementerId { get; private set; } public string Name { get; private set; } = string.Empty; public double Price { get; set; } public DateOnly DateOfReceipt { get; private set; } public DateOnly DateOfPassage { get; private set; } private Dictionary? _cachedClients = null; [NotMapped] public Dictionary StudentsModel => _cachedClients ??= Students.Select(x => (StudentByDisciplineModel)x).ToDictionary(x => x.StudentId, x => x); public int Id { get; private set; } [Required] public Implementer? Student { get; private set; } [Required] public List Students { get; private set; } = new(); [Required] public List Requirements { get; private set; } = new(); public static Discipline Create(DisciplineBindingModel model) => model.CastWithCommonProperties(); public static implicit operator DisciplineViewModel?(Discipline? model) { if (model == null) { return null; } model._cachedClients = null; var res = model.CastWithCommonProperties(); res.DirectorLogin = model.Student?.Login ?? string.Empty; res.RequirementViewModels = model.Requirements? .Select(x => (RequirementViewModel)x.Requirement) .ToList() ?? new(); foreach (var studentByDiscipline in model.Students) { if (studentByDiscipline.Student != null) { res.StudenttViewModels.Add(studentByDiscipline.Student.GetViewModel()); } else { res.StudentViewModels = new(); break; } } return res; } public void Update(DisciplineBindingModel model) { Price = model.Price; DateOfPassage = model.DateOfPassage; } public void UpdateClients(SchoolDB context, DisciplineBindingModel model) { var oldStudents = context.StudentsByDisciplines.Where(x => x.DisciplineId == model.Id).ToDictionary(x => x.StudentId, x => x); var newStudents = model.StudentsModel.ToDictionary( x => x.Key, x => { var res = x.Value.CastWithCommonProperties(); res.StudentId = x.Key; res.DisciplineId = Id; return res; }); context.RemoveRange(oldStudents.Where(x => !newStudents.ContainsKey(x.Key)).Select(x => x.Value)); context.SaveChanges(); context.AddRange (newStudents.Where(x => !oldStudents.ContainsKey(x.Key)).Select(x => x.Value)); oldStudents .Where(x => newStudents.ContainsKey(x.Key)) .Select(x => x.Value).ToList() .ForEach(x => x.DateOfClient = newStudents[x.StudentId].DateOfStudent); context.SaveChanges(); _cachedClients = null; } } }