using SchoolAgainStudyContracts.BindingModel; using SchoolAgainStudyContracts.ViewModel; using SchoolAgainStudyDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace SchoolAgainStudyDataBaseImplements.Models { public class Teacher : ITeacher { [Required] public string Name { get; set; } = string.Empty; [Required] public string Post { get; set; } = string.Empty; [Required] public string Phone { get; set; } = string.Empty; [Required] public string Login { get; set; } = string.Empty; [Required] public string Password { get; set; } = string.Empty; private Dictionary? _TeacherMaterials = null; [NotMapped] public Dictionary TeacherMaterials { get { if (_TeacherMaterials == null) { _TeacherMaterials = Materials .ToDictionary(recPC => recPC.MaterialId, recPC => (recPC.Material as IMaterial)); } return _TeacherMaterials; } } public int Id { get; set; } [ForeignKey("TeacherId")] public virtual List Materials { get; set; } = new(); [ForeignKey("TeacherId")] public virtual List Tasks { get; set; } = new(); [ForeignKey("TeacherId")] public virtual List Lessons { get; set; } = new(); public static Teacher Create(SchoolDataBase context, TeacherBindingModel model) { return new Teacher() { Id = model.Id, Name = model.Name, Post = model.Post, Phone = model.Phone, Login = model.Login, Password = model.Password, Materials = model.TeacherMaterials.Select(x => new TeacherMaterial { Material = context.Materials.First(y => y.Id == x.Key), }).ToList() }; } public void Update(TeacherBindingModel model) { Name = model.Name; Post = model.Post; Phone = model.Phone; Login = model.Login; Password = model.Password; } public TeacherViewModel GetViewModel => new() { Id = Id, Name = Name, Post = Post, Phone = Phone, Login = Login, Password = Password, TeacherMaterials = TeacherMaterials }; public void UpdateMaterials(SchoolDataBase context, TeacherBindingModel model) { var teacherMaterials = context.TeacherMaterials.Where(rec => rec.TeacherId == model.Id).ToList(); if (teacherMaterials != null && teacherMaterials.Count > 0) { context.TeacherMaterials.RemoveRange(teacherMaterials.Where(rec => !model.TeacherMaterials.ContainsKey(rec.MaterialId))); context.SaveChanges(); foreach (var updateMaterial in teacherMaterials) { model.TeacherMaterials.Remove(updateMaterial.MaterialId); } context.SaveChanges(); } var teacher = context.Teachers.First(x => x.Id == Id); foreach (var pc in model.TeacherMaterials) { context.TeacherMaterials.Add(new TeacherMaterial { Teacher = teacher, Material = context.Materials.First(x => x.Id == pc.Key), }); context.SaveChanges(); } _TeacherMaterials = null; } } }