ISEbd-22_CourseWork_School/School/SchoolDataBaseImplement/Models/Discipline.cs

99 lines
3.7 KiB
C#

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<int, StudentByDisciplineModel>? _cachedClients = null;
[NotMapped]
public Dictionary<int, StudentByDisciplineModel> 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<StudentByDiscipline> Students { get; private set; } = new();
[Required]
public List<RequirementByDiscipline> Requirements { get; private set; } = new();
public static Discipline Create(DisciplineBindingModel model) =>
model.CastWithCommonProperties<Discipline, DisciplineBindingModel>();
public static implicit operator DisciplineViewModel?(Discipline? model)
{
if (model == null)
{
return null;
}
model._cachedClients = null;
var res = model.CastWithCommonProperties<DisciplineViewModel, Discipline>();
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<StudentByDiscipline, StudentByDisciplineModel>();
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;
}
}
}