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

79 lines
3.2 KiB
C#
Raw Permalink Normal View History

2024-05-01 17:54:58 +04:00
using SchoolContracts.BindingModels;
using SchoolContracts.Extensions;
using SchoolContracts.ViewModels;
using SchoolDataModels;
using System.ComponentModel.DataAnnotations;
using SchoolDataModels.Models;
namespace SchoolDatabaseImplement.Models
{
public class Requirement : IRequirementModel
{
[Required]
public int ExecutorId { get; private set; }
[Required]
public string NameOfRequirement { get; private set; } = string.Empty;
public int Id { get; private set; }
[Required]
public double Price { get; private set; }
private Dictionary<int, RequirementByDisciplineModel>? _cachedDisciplines;
public Dictionary<int, RequirementByDisciplineModel> DisciplinesModels =>
_cachedDisciplines ??= Disciplines.Select(x => (RequirementByDisciplineModel)x).ToDictionary(x => x.DisciplineId, x => x);
[Required]
public Executor? Executor { get; private set; }
[Required]
public List<RequirementByDiscipline> Disciplines { get; private set; } = new();
public static Requirement Create(RequirementBindingModel model) => model.CastWithCommonProperties<Requirement, RequirementBindingModel>();
public static implicit operator RequirementViewModel(Requirement? model)
{
if (model == null)
{
throw new ArgumentNullException("Возникла ошибка при попытки получить View-модель из null-объекта", nameof(model));
}
model._cachedDisciplines = null;
var result = model.CastWithCommonProperties<RequirementViewModel, Requirement>();
result.ExecutorLogin = model.Executor?.Login ?? string.Empty;
return result;
}
public void Update(RequirementBindingModel model)
{
Price = model.Price;
}
/// <summary>
/// Привязка требований к дисциплиным
/// </summary>
public void UpdateDisciplines(SchoolDB context, RequirementBindingModel model)
{
var oldDisciplines = context.RequirementByDisciplines.Where(x => x.DisciplineId == model.Id).ToDictionary(x => x.DisciplineId, x => x);
var newDisciplines = model.DisciplinesModels.ToDictionary(
x => x.Key,
x =>
{
var res = x.Value.CastWithCommonProperties<RequirementByDiscipline, RequirementByDisciplineModel>();
res.RequirementId = model.Id;
res.DisciplineId = x.Key;
return res;
});
context.RemoveRange(oldDisciplines.Where(x => !newDisciplines.ContainsKey(x.Key)).Select(x => x.Value));
context.SaveChanges();
context.AddRange (newDisciplines.Where(x => !oldDisciplines.ContainsKey(x.Key)).Select(x => x.Value));
oldDisciplines.Where(x => newDisciplines.ContainsKey(x.Key))
.Select(x => x.Value).ToList()
.ForEach(x => x.Count = newDisciplines[x.DisciplineId].Count);
context.SaveChanges();
_cachedDisciplines = null;
}
}
}