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.Text; using System.Threading.Tasks; namespace SchoolAgainStudyDataBaseImplements.Models { public class Task : ITask { [Required] public string Title { get; set; } = string.Empty; [Required] public DateTime DateIssue { get; set; } [Required] public DateTime DateDelivery { get; set; } [Required] public int TeacherId { get; set; } public string TeacherName { get; set; } = string.Empty; public virtual Teacher Teacher { get; set; } private Dictionary? _TaskMaterials = null; [NotMapped] public Dictionary TaskMaterials { get { if (_TaskMaterials == null) { _TaskMaterials = Materials .ToDictionary(recPC => recPC.MaterialId, recPC => (recPC.Material as IMaterial)); } return _TaskMaterials; } } public int Id { get; set; } [ForeignKey("TaskId")] public virtual List Materials { get; set; } = new(); [ForeignKey("TaskId")] public virtual List Diys { get; set; } = new(); public static Task Create(SchoolDataBase context, TaskBindingModel model) { return new Task() { Id = model.Id, Title = model.Title, DateIssue = model.DateIssue, DateDelivery = model.DateDelivery, TeacherId = model.TeacherId, TeacherName = model.TeacherName, Materials = model.TaskMaterials.Select(x => new TaskMaterial { Material = context.Materials.First(y => y.Id == x.Key), }).ToList() }; } public void Update(TaskBindingModel model) { Title = model.Title; DateIssue = model.DateIssue; DateDelivery = model.DateDelivery; } public TaskViewModel GetViewModel => new() { Id = Id, Title = Title, DateIssue = DateIssue, DateDelivery = DateDelivery, TeacherId = TeacherId, TeacherName= TeacherName, TaskMaterials = TaskMaterials }; public void UpdateMaterials(SchoolDataBase context, TaskBindingModel model) { var taskMaterials = context.TaskMaterials.Where(rec => rec.TaskId == model.Id).ToList(); if (taskMaterials != null && taskMaterials.Count > 0) { context.TaskMaterials.RemoveRange(taskMaterials.Where(rec => !model.TaskMaterials.ContainsKey(rec.MaterialId))); context.SaveChanges(); foreach (var updateMaterial in taskMaterials) { model.TaskMaterials.Remove(updateMaterial.MaterialId); } context.SaveChanges(); } var task = context.Tasks.First(x => x.Id == Id); foreach (var pc in model.TaskMaterials) { context.TaskMaterials.Add(new TaskMaterial { Task = task, Material = context.Materials.First(x => x.Id == pc.Key), }); context.SaveChanges(); } _TaskMaterials = null; } } }