CourseWork_Borschevskaya_A..../Hospital/HospitalDatabaseImplement/Models/Treatment.cs

108 lines
3.8 KiB
C#

using HospitalContracts.BindingModels;
using HospitalContracts.ViewModels;
using HospitalDataModels.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;
using System.Xml.Linq;
namespace HospitalDatabaseImplement.Models
{
public class Treatment : ITreatmentModel
{
public int Id { get; private set; }
[Required]
[MaxLength(55)]
public string Name { get; private set; } = string.Empty;
private Dictionary<int, IProcedureModel>? _treatmentProcedures = null;
[NotMapped]
public Dictionary<int, IProcedureModel> TreatmentProcedures {
get
{
if (_treatmentProcedures == null)
{
_treatmentProcedures = Procedures
.ToDictionary(rec => rec.ProcedureId, rec =>
rec.Procedure as IProcedureModel);
}
return _treatmentProcedures;
}
}
[ForeignKey("TreatmentId")]
public virtual List<Patient> Patients { get; set; } = new();
[ForeignKey("TreatmentId")]
public virtual List<TreatmentProcedure> Procedures { get; set; } = new();
[ForeignKey("TreatmentId")]
public virtual List<RecipeTreatment> Recipes { get; set; } = new();
public static Treatment Create(HospitalDatabase context, TreatmentBindingModel model)
{
return new Treatment()
{
Id = model.Id,
Name = model.Name,
Procedures = model.TreatmentProcedures.Select(x => new TreatmentProcedure
{
Procedure = context.Procedures.First(y => y.Id == x.Key),
}).ToList()
};
}
public static Treatment? Create(HospitalDatabase context, XElement element)
{
if (element == null)
{
return null;
}
return new Treatment()
{
Name = element.Element("Name")!.Value,
Procedures = element.Element("Procedures")!.Elements("ProcedureId").Select( x => new TreatmentProcedure
{
Procedure = context.Procedures.First(y => y.Id == Convert.ToInt32(x.Value))
}).ToList()
};
}
public void Update(TreatmentBindingModel model)
{
Name = model.Name;
}
public TreatmentViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
TreatmentProcedures = TreatmentProcedures
};
public void UpdateProcedures(HospitalDatabase context, TreatmentBindingModel model)
{
var treatmentProcedures = context.TreatmentProcedures.Where(rec => rec.TreatmentId == model.Id).ToList();
if (treatmentProcedures != null && treatmentProcedures.Count > 0)
{
context.TreatmentProcedures.RemoveRange(treatmentProcedures.Where(rec
=> !model.TreatmentProcedures.ContainsKey(rec.ProcedureId)));
context.SaveChanges();
}
var treatment = context.Treatments.First(x => x.Id == Id);
foreach (var pc in model.TreatmentProcedures)
{
context.TreatmentProcedures.Add(new TreatmentProcedure
{
Treatment = treatment,
Procedure = context.Procedures.First(x => x.Id == pc.Key),
});
context.SaveChanges();
}
_treatmentProcedures = null;
}
}
}