CourseWork_Borschevskaya_A..../Hospital/HospitalDatabaseImplement/LoaderFromXML.cs

63 lines
2.2 KiB
C#

using HospitalDatabaseImplement.Models;
using System.Xml.Linq;
namespace HospitalDatabaseImplement
{
public class LoaderFromXML
{
private static readonly string PatientFileName = "XMLData\\Patient.xml";
private static readonly string TreatmentFileName = "XMLData\\Treatment.xml";
private static readonly string ProcedureFileName = "XMLData\\Procedure.xml";
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
return XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
}
return new List<T>();
}
public static void LoadPatients()
{
// TODO return LoadData(PatientFileName, "Patient", x => Patient.Create(x)!)!;
using var context = new HospitalDatabase();
var list = LoadData(PatientFileName, "Patient", x => Patient.Create(x)!)!;
list.ForEach(x =>
{
context.Patients.Add(x);
context.SaveChanges();
});
}
public static void LoadTreatments()
{
using var context = new HospitalDatabase();
if (context.Treatments.ToList().Count > 0)
return;
var list = LoadData(TreatmentFileName, "Treatment", x => Treatment.Create(context, x)!)!;
list.ForEach(x =>
{
context.Treatments.Add(x);
});
context.SaveChanges();
}
public static void LoadProcedures()
{
using var context = new HospitalDatabase();
if (context.Procedures.ToList().Count > 0)
return;
// TODO return LoadData(ProcedureFileName, "Procedure", x => Procedure.Create(context, x)!)!;
var list = LoadData(ProcedureFileName, "Procedure", x => Procedure.Create(context, x)!)!;
list.ForEach(x =>
{
context.Procedures.Add(x);
context.SaveChanges();
});
}
}
}