104 lines
3.5 KiB
C#
104 lines
3.5 KiB
C#
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; }
|
|
|
|
public int TeacherId { get; set; }
|
|
private Dictionary<int, IMaterial>? _TaskMaterials = null;
|
|
[NotMapped]
|
|
public Dictionary<int, IMaterial> 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<TaskMaterial> Materials { get; set; } = new();
|
|
[ForeignKey("TaskId")]
|
|
public virtual List<Diy> 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,
|
|
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,
|
|
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;
|
|
}
|
|
}
|
|
}
|