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

86 lines
2.9 KiB
C#

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);
context.SaveChanges();
}
var symptom = context.Symptomes.First(x => x.Id == model.Id);
foreach (var pc in model.SymptomDiagnoses)
{
context.SymptomDiagnoses.Add(new SymptomDiagnose
{
Symptom = symptom,
Diagnose = context.Diagnoses.First(x => x.Id == pc.Key),
});
context.SaveChanges();
}
_symptomDiagnoses = null;
}
}
}