PIbd-21_CourseWork_Polyclin.../Polyclinic/PolyclinicDatabaseImplement/Models/Symptom.cs

87 lines
3.1 KiB
C#
Raw Normal View History

using PolyclinicContracts.BindingModels;
using PolyclinicContracts.ViewModels;
using PolyclinicDataModels.Models;
using SecuritySystemDatabaseImplement;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PolyclinicDatabaseImplement.Models
{
public class Symptom : ISymptomModel
{
[Required]
public string Name { get; set; } = string.Empty;
public string Comment { get; set; } = string.Empty;
[ForeignKey("SymptomId")]
public virtual List<SymptomDiagnose> Diagnoses { get; set; } = new();
private Dictionary<int, IDiagnoseModel>? _symptomDiagnoses = null;
[NotMapped]
public Dictionary<int, IDiagnoseModel> SymptomDiagnoses
{
get
{
if (_symptomDiagnoses == null)
{
_symptomDiagnoses = Diagnoses.ToDictionary(
symptomDiagnose => symptomDiagnose.DiagnoseId,
symptomDiagnose => symptomDiagnose.Diagnose as IDiagnoseModel
);
}
return _symptomDiagnoses;
}
}
public int Id { get; set; }
public static Symptom Create(PolyclinicDatabase context, SymptomBindingModel model)
{
return new Symptom()
{
Id = model.Id,
Name = model.Name,
Comment = model.Comment,
Diagnoses = model.SymptomDiagnoses.Select(symptomDiagnose => new SymptomDiagnose
{
Diagnose = context.Diagnoses.First(diagnose => diagnose.Id == symptomDiagnose.Key)
}).ToList()
};
}
public void Update(SymptomBindingModel model)
{
Comment = model.Comment;
Name = model.Name;
}
public SymptomViewModel GetViewModel => new()
{
Id = Id,
Comment = Comment,
Name = Name,
SymptomDiagnoses = SymptomDiagnoses
};
public void UpdateDiagnoses(PolyclinicDatabase context, SymptomBindingModel model)
{
var symptomDiagnoses = context.SymptomDiagnoses.Where(rec => rec.SymptomId == model.Id).ToList();
if (symptomDiagnoses != null && symptomDiagnoses.Count > 0)
{
// удалили те, которых нет в модели
context.SymptomDiagnoses.RemoveRange(symptomDiagnoses
.Where(rec => !model.SymptomDiagnoses.ContainsKey(rec.DiagnoseId)));
context.SaveChanges();
}
var course = context.Symptomes.First(x => x.Id == Id);
foreach (var pc in model.SymptomDiagnoses)
{
context.SymptomDiagnoses.Add(new SymptomDiagnose
{
Symptom = course,
Diagnose = context.Diagnoses.First(x => x.Id == pc.Key),
});
context.SaveChanges();
}
_symptomDiagnoses = null;
}
}
}