DatabaseImplement

This commit is contained in:
parent 4870dbb8b5
commit 9dee5eaa47
24 changed files with 2066 additions and 12 deletions

View File

@ -3,9 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HospitalDataModels", "HospitalDataModels\HospitalDataModels.csproj", "{DEC0CC7C-0315-4D11-B383-F5CD19DA7E15}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HospitalDataModels", "HospitalDataModels\HospitalDataModels.csproj", "{DEC0CC7C-0315-4D11-B383-F5CD19DA7E15}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HospitalContracts", "HospitalContracts\HospitalContracts.csproj", "{435124E0-E0A5-4EB8-A46C-C093C47A65F7}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HospitalContracts", "HospitalContracts\HospitalContracts.csproj", "{435124E0-E0A5-4EB8-A46C-C093C47A65F7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HospitalDatabaseImplement", "HospitalDatabaseImplement\HospitalDatabaseImplement.csproj", "{595F63B0-79FF-4EBA-9582-2A0652D00B58}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -21,6 +23,10 @@ Global
{435124E0-E0A5-4EB8-A46C-C093C47A65F7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{435124E0-E0A5-4EB8-A46C-C093C47A65F7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{435124E0-E0A5-4EB8-A46C-C093C47A65F7}.Release|Any CPU.Build.0 = Release|Any CPU
{595F63B0-79FF-4EBA-9582-2A0652D00B58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{595F63B0-79FF-4EBA-9582-2A0652D00B58}.Debug|Any CPU.Build.0 = Debug|Any CPU
{595F63B0-79FF-4EBA-9582-2A0652D00B58}.Release|Any CPU.ActiveCfg = Release|Any CPU
{595F63B0-79FF-4EBA-9582-2A0652D00B58}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -30,15 +30,5 @@ namespace HospitalContracts.SearchModels
/// Идентификатор лечащего врача
/// </summary>
public int? DoctorId { get; set; }
/// <summary>
/// Начало периода выборки данных для отчета
/// </summary>
public DateTime? DateFrom { get; set; }
/// <summary>
/// Конец периода выборки данных для отчета
/// </summary>
public DateTime? DateTo { get; set; }
}
}

View File

@ -20,5 +20,15 @@ namespace HospitalContracts.SearchModels
/// Идентификатор доктора
/// </summary>
public int? DoctorId { get; set; }
/// <summary>
/// Начало периода выборки данных для отчета
/// </summary>
public DateTime? DateFrom { get; set; }
/// <summary>
/// Конец периода выборки данных для отчета
/// </summary>
public DateTime? DateTo { get; set; }
}
}

View File

@ -0,0 +1,85 @@
using HospitalDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement
{
/// <summary>
/// Класс для взаимодействия с базой данных
/// </summary>
public class HospitalDatabase : DbContext
{
/// <summary>
/// Параметры подключения к базе данных
/// </summary>
private string _dbConnectionString = @"Data Source=FACTORINO\SQLEXPRESS;Initial Catalog=HospitalDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True";
/// <summary>
/// Подключение к базе данных
/// </summary>
/// <param name="optionsBuilder"></param>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(_dbConnectionString);
}
base.OnConfiguring(optionsBuilder);
}
/// <summary>
/// Таблица "Доктора"
/// </summary>
public virtual DbSet<Doctor> Doctors { get; set; }
/// <summary>
/// Таблица "Пациенты"
/// </summary>
public virtual DbSet<Patient> Patients { get; set; }
/// <summary>
/// Таблица "Рецепты"
/// </summary>
public virtual DbSet<Recipe> Recipes { get; set; }
/// <summary>
/// Таблица "Болезни"
/// </summary>
public virtual DbSet<Disease> Diseases { get; set; }
/// <summary>
/// Таблица "Процедуры"
/// </summary>
public virtual DbSet<Procedure> Procedures { get; set; }
/// <summary>
/// Таблица "Лекарства"
/// </summary>
public virtual DbSet<Medicine> Medicines { get; set; }
/// <summary>
/// Таблица связи для сущностей "Пациент" и "Рецепт"
/// </summary>
public virtual DbSet<PatientRecipe> PatientRecipes { get; set; }
/// <summary>
/// Таблица связи для сущностей "Пациент" и "Процедура"
/// </summary>
public virtual DbSet<PatientProcedure> PatientProcedures { get; set; }
/// <summary>
/// Таблица связи для сущностей "Рецепт" и "Лекарство"
/// </summary>
public virtual DbSet<RecipeMedicine> RecipeMedicines { get; set; }
/// <summary>
/// Таблица связи для сущностей "Процедура" и "Лекарство"
/// </summary>
public virtual DbSet<ProcedureMedicine> ProcedureMedicines { get; set; }
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\HospitalContracts\HospitalContracts.csproj" />
<ProjectReference Include="..\HospitalDataModels\HospitalDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.13">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,154 @@
using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Болезнь"
/// </summary>
public class DiseaseStorage : IDiseaseStorage
{
/// <summary>
/// Получить полный список
/// </summary>
/// <returns></returns>
public List<DiseaseViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Diseases
.Include(x => x.Recipe)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить фильтрованный список
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<DiseaseViewModel> GetFilteredList(DiseaseSearchModel model)
{
using var context = new HospitalDatabase();
// Фильтрация по идентификатору рецепта
if (model.RecipeId.HasValue)
{
return context.Diseases
.Include(x => x.Recipe)
.Where(x => x.RecipeId.Equals(model.RecipeId))
.Select(x => x.GetViewModel)
.ToList();
}
// Фильтрация по названию болезни
if (!string.IsNullOrEmpty(model.Name))
{
return context.Diseases
.Include(x => x.Recipe)
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
/// <summary>
/// Получить элемент списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DiseaseViewModel? GetElement(DiseaseSearchModel model)
{
using var context = new HospitalDatabase();
// Поиск по идентификатору
if (model.Id.HasValue)
{
return context.Diseases
.Include(x => x.Recipe)
.FirstOrDefault(x => x.Id.Equals(model.Id))
?.GetViewModel;
}
// Поиск по названию болезни
if (!string.IsNullOrEmpty(model.Name))
{
return context.Diseases
.Include(x => x.Recipe)
.FirstOrDefault(x => x.Name.Equals(model.Name))
?.GetViewModel;
}
return null;
}
/// <summary>
/// Добавить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DiseaseViewModel? Insert(DiseaseBindingModel model)
{
using var context = new HospitalDatabase();
var newDisease = Disease.Create(context, model);
if (newDisease == null)
{
return null;
}
context.Diseases.Add(newDisease);
context.SaveChanges();
return newDisease.GetViewModel;
}
/// <summary>
/// Редактировать элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DiseaseViewModel? Update(DiseaseBindingModel model)
{
using var context = new HospitalDatabase();
var disease = context.Diseases
.Include(x => x.Recipe)
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (disease == null)
{
return null;
}
disease.Update(model);
context.SaveChanges();
return disease.GetViewModel;
}
/// <summary>
/// Удалить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DiseaseViewModel? Delete(DiseaseBindingModel model)
{
using var context = new HospitalDatabase();
var disease = context.Diseases
.Include(x => x.Recipe)
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (disease == null)
{
return null;
}
context.Diseases.Remove(disease);
context.SaveChanges();
return disease.GetViewModel;
}
}
}

View File

@ -0,0 +1,155 @@
using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Доктор"
/// </summary>
public class DoctorStorage : IDoctorStorage
{
/// <summary>
/// Получить полный список
/// </summary>
/// <returns></returns>
public List<DoctorViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Doctors
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить фильтрованный список
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<DoctorViewModel> GetFilteredList(DoctorSearchModel model)
{
using var context = new HospitalDatabase();
// Фильтрация по ФИО
if (!string.IsNullOrEmpty(model.FullName))
{
return context.Doctors
.Where(x => x.FullName.Contains(model.FullName))
.Select(x => x.GetViewModel)
.ToList();
}
// Фильтрация по логину
if (!string.IsNullOrEmpty(model.Email))
{
return context.Doctors
.Where(x => x.Email.Contains(model.Email))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
/// <summary>
/// Получить элемент списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DoctorViewModel? GetElement(DoctorSearchModel model)
{
using var context = new HospitalDatabase();
// Поиск по идентификатору
if (model.Id.HasValue)
{
return context.Doctors
.FirstOrDefault(x => x.Id.Equals(model.Id))
?.GetViewModel;
}
// Поиск по логину и паролю
if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password))
{
return context.Doctors
.FirstOrDefault(x => x.Email.Equals(model.Email) && x.Password.Equals(model.Password))
?.GetViewModel;
}
// Поиск по логину
if (!string.IsNullOrEmpty(model.Email))
{
return context.Doctors
.FirstOrDefault(x => x.Email.Equals(model.Email))
?.GetViewModel;
}
return null;
}
/// <summary>
/// Добавить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DoctorViewModel? Insert(DoctorBindingModel model)
{
using var context = new HospitalDatabase();
var newDoctor = Doctor.Create(model);
if (newDoctor == null)
{
return null;
}
context.Doctors.Add(newDoctor);
context.SaveChanges();
return newDoctor.GetViewModel;
}
/// <summary>
/// Редактировать элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DoctorViewModel? Update(DoctorBindingModel model)
{
using var context = new HospitalDatabase();
var doctor = context.Doctors
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (doctor == null)
{
return null;
}
doctor.Update(model);
context.SaveChanges();
return doctor.GetViewModel;
}
/// <summary>
/// Удалить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DoctorViewModel? Delete(DoctorBindingModel model)
{
using var context = new HospitalDatabase();
var doctor = context.Doctors
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (doctor == null)
{
return null;
}
context.Doctors.Remove(doctor);
context.SaveChanges();
return doctor.GetViewModel;
}
}
}

View File

@ -0,0 +1,138 @@
using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Лекарство"
/// </summary>
public class MedicineStorage : IMedicineStorage
{
/// <summary>
/// Получить полный список
/// </summary>
/// <returns></returns>
public List<MedicineViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Medicines
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить фильтрованный список
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<MedicineViewModel> GetFilteredList(MedicineSearchModel model)
{
using var context = new HospitalDatabase();
// Фильтрация по названию лекарства
if (!string.IsNullOrEmpty(model.Name))
{
return context.Medicines
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
/// <summary>
/// Получить элемент списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public MedicineViewModel? GetElement(MedicineSearchModel model)
{
using var context = new HospitalDatabase();
// Поиск по идентификатору
if (model.Id.HasValue)
{
return context.Medicines
.FirstOrDefault(x => x.Id.Equals(model.Id))
?.GetViewModel;
}
// Поиск по названию лекарства
if (!string.IsNullOrEmpty(model.Name))
{
return context.Medicines
.FirstOrDefault(x => x.Name.Equals(model.Name))
?.GetViewModel;
}
return null;
}
/// <summary>
/// Добавить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public MedicineViewModel? Insert(MedicineBindingModel model)
{
using var context = new HospitalDatabase();
var newMedicine = Medicine.Create(model);
if (newMedicine == null)
{
return null;
}
context.Medicines.Add(newMedicine);
context.SaveChanges();
return newMedicine.GetViewModel;
}
/// <summary>
/// Редактировать элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public MedicineViewModel? Update(MedicineBindingModel model)
{
using var context = new HospitalDatabase();
var medicine = context.Medicines
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (medicine == null)
{
return null;
}
medicine.Update(model);
context.SaveChanges();
return medicine.GetViewModel;
}
/// <summary>
/// Удалить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public MedicineViewModel? Delete(MedicineBindingModel model)
{
using var context = new HospitalDatabase();
var medicine = context.Medicines
.FirstOrDefault(x => x.Equals(model.Id));
if (medicine == null)
{
return null;
}
context.Medicines.Remove(medicine);
context.SaveChanges();
return medicine.GetViewModel;
}
}
}

View File

@ -0,0 +1,189 @@
using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Пациент"
/// </summary>
public class PatientStorage : IPatientStorage
{
/// <summary>
/// Получить полный список
/// </summary>
/// <returns></returns>
public List<PatientViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Patients
.Include(x => x.Doctor)
.Include(x => x.Recipes)
.ThenInclude(x => x.Recipe)
.Include(x => x.Procedures)
.ThenInclude(x => x.Procedure)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить фильтрованный список
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<PatientViewModel> GetFilteredList(PatientSearchModel model)
{
using var context = new HospitalDatabase();
// Фильтрация по идентификатору лечащего врача
if (model.DoctorId.HasValue)
{
return context.Patients
.Include(x => x.Doctor)
.Include(x => x.Recipes)
.ThenInclude(x => x.Recipe)
.Include(x => x.Procedures)
.ThenInclude(x => x.Procedure)
.Where(x => x.DoctorId.Equals(model.DoctorId))
.Select(x => x.GetViewModel)
.ToList();
}
// Фильтрация по ФИО
if (!string.IsNullOrEmpty(model.FullName))
{
return context.Patients
.Include(x => x.Doctor)
.Include(x => x.Recipes)
.ThenInclude(x => x.Recipe)
.Include(x => x.Procedures)
.ThenInclude (x => x.Procedure)
.Where(x => x.FullName.Contains(model.FullName))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
/// <summary>
/// Получить элемент списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public PatientViewModel? GetElement(PatientSearchModel model)
{
using var context = new HospitalDatabase();
// Поиск по идентификатору
if (model.Id.HasValue)
{
return context.Patients
.Include(x => x.Doctor)
.Include(x => x.Recipes)
.ThenInclude(x => x.Recipe)
.Include(x => x.Procedures)
.ThenInclude(x => x.Procedure)
.FirstOrDefault(x => x.Id.Equals(model.Id))
?.GetViewModel;
}
// Поиск по номеру телефона
if (!string.IsNullOrEmpty(model.Phone))
{
return context.Patients
.Include(x => x.Doctor)
.Include(x => x.Recipes)
.ThenInclude(x => x.Recipe)
.Include(x => x.Procedures)
.ThenInclude(x => x.Procedure)
.FirstOrDefault(x => x.Phone.Equals(model.Phone))
?.GetViewModel;
}
return null;
}
/// <summary>
/// Добавить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public PatientViewModel? Insert(PatientBindingModel model)
{
using var context = new HospitalDatabase();
var newPatient = Patient.Create(context, model);
if (newPatient == null)
{
return null;
}
context.Patients.Add(newPatient);
context.SaveChanges();
return newPatient.GetViewModel;
}
/// <summary>
/// Редактировать элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public PatientViewModel? Update(PatientBindingModel model)
{
using var context = new HospitalDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var patient = context.Patients
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (patient == null)
{
return null;
}
patient.Update(model);
context.SaveChanges();
patient.UpdateRecipes(context, model);
patient.UpdateProcedures(context, model);
transaction.Commit();
return patient.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
/// <summary>
/// Удалить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public PatientViewModel? Delete(PatientBindingModel model)
{
using var context = new HospitalDatabase();
var patient = context.Patients
.Include(x => x.Doctor)
.Include(x => x.Recipes)
.ThenInclude(x => x.Recipe)
.Include(x => x.Procedures)
.ThenInclude(x => x.Procedure)
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (patient == null)
{
return null;
}
context.Patients.Remove(patient);
context.SaveChanges();
return patient.GetViewModel;
}
}
}

View File

@ -0,0 +1,162 @@
using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace HospitalDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Процедура"
/// </summary>
public class ProcedureStorage : IProcedureStrorage
{
/// <summary>
/// Получить полный список
/// </summary>
/// <returns></returns>
public List<ProcedureViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Procedures
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить фильтрованный список
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ProcedureViewModel> GetFilteredList(ProcedureSearchModel model)
{
using var context = new HospitalDatabase();
// Фильтрация по названию процедуры
if (!string.IsNullOrEmpty(model.Name))
{
return context.Procedures
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
/// <summary>
/// Получить элемент списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ProcedureViewModel? GetElement(ProcedureSearchModel model)
{
using var context = new HospitalDatabase();
// Поиск по идентификатору
if (model.Id.HasValue)
{
return context.Procedures
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.FirstOrDefault(x => x.Id.Equals(model.Id))
?.GetViewModel;
}
// Поиск по названию процедуры
if (!string.IsNullOrEmpty(model.Name))
{
return context.Procedures
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.FirstOrDefault(x => x.Name.Equals(model.Name))
?.GetViewModel;
}
return null;
}
/// <summary>
/// Добавить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ProcedureViewModel? Insert(ProcedureBindingModel model)
{
using var context = new HospitalDatabase();
var newProcedure = Procedure.Create(context, model);
if (newProcedure == null)
{
return null;
}
context.Procedures.Add(newProcedure);
context.SaveChanges();
return newProcedure.GetViewModel;
}
/// <summary>
/// Редактировать элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ProcedureViewModel? Update(ProcedureBindingModel model)
{
using var context = new HospitalDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var procedure = context.Procedures
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.FirstOrDefault(x => x.Id.Equals(model.Id));
if (procedure == null)
{
return null;
}
procedure.Update(model);
context.SaveChanges();
procedure.UpdateMedicines(context, model);
transaction.Commit();
return procedure.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
/// <summary>
/// Удалить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ProcedureViewModel? Delete(ProcedureBindingModel model)
{
using var context = new HospitalDatabase();
var procedure = context.Procedures
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.FirstOrDefault(x => x.Equals(model.Id));
if (procedure == null)
{
return null;
}
context.Procedures.Remove(procedure);
context.SaveChanges();
return procedure.GetViewModel;
}
}
}

View File

@ -0,0 +1,168 @@
using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Implements
{
/// <summary>
/// Хранилище для сущности "Рецепт"
/// </summary>
public class RecipeStorage : IRecipeStorage
{
/// <summary>
/// Получить полный список
/// </summary>
/// <returns></returns>
public List<RecipeViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Recipes
.Include(x => x.Doctor)
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получить фильтрованный список
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<RecipeViewModel> GetFilteredList(RecipeSearchModel model)
{
using var context = new HospitalDatabase();
// Получения всех записей для фильтрации по одному или нескольким параметрам
var recipes = context.Recipes
.Include(x => x.Doctor)
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.Select(x => x.GetViewModel)
.ToList();
// Фильтрация по идентификатору доктора
if (model.DoctorId.HasValue)
{
recipes = recipes
.Where(x => x.DoctorId.Equals(model.DoctorId))
.ToList();
}
// Фильтрация по датам
if (model.DateFrom.HasValue && model.DateTo.HasValue)
{
recipes = recipes
.Where(x => x.IssueDate >= model.DateFrom && x.IssueDate <= model.DateTo)
.ToList();
}
return recipes ?? new();
}
/// <summary>
/// Получить элемент списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RecipeViewModel? GetElement(RecipeSearchModel model)
{
using var context = new HospitalDatabase();
// Поиск по идентификатору
if (model.Id.HasValue)
{
return context.Recipes
.Include(x => x.Doctor)
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.FirstOrDefault(x => x.Id.Equals(model.Id))
?.GetViewModel;
}
return null;
}
/// <summary>
/// Добавить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RecipeViewModel? Insert(RecipeBindingModel model)
{
using var context = new HospitalDatabase();
var newRecipe = Recipe.Create(context, model);
if (newRecipe == null)
{
return null;
}
context.Recipes.Add(newRecipe);
context.SaveChanges();
return newRecipe.GetViewModel;
}
/// <summary>
/// Редактировать элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RecipeViewModel? Update(RecipeBindingModel model)
{
using var context = new HospitalDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var recipe = context.Recipes
.Include(x => x.Doctor)
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.FirstOrDefault(rec => rec.Id == model.Id);
if (recipe == null)
{
return null;
}
recipe.Update(model);
context.SaveChanges();
recipe.UpdateMedicines(context, model);
transaction.Commit();
return recipe.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
/// <summary>
/// Удалить элемент
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public RecipeViewModel? Delete(RecipeBindingModel model)
{
using var context = new HospitalDatabase();
var recipe = context.Recipes
.Include(x => x.Doctor)
.Include(x => x.Medicines)
.ThenInclude(x => x.Medicine)
.FirstOrDefault(x => x.Equals(model.Id));
if (recipe == null)
{
return null;
}
context.Recipes.Remove(recipe);
context.SaveChanges();
return recipe.GetViewModel;
}
}
}

View File

@ -0,0 +1,98 @@
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;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Сущность "Болезнь"
/// </summary>
public class Disease : IDiseaseModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Название болезни
/// </summary>
[Required]
[MaxLength(30)]
public string Name { get; private set; } = string.Empty;
/// <summary>
/// Симптомы заболевания
/// </summary>
[MaxLength(100)]
public string? Symptoms { get; private set; }
/// <summary>
/// Идентификатор рецепта
/// </summary>
[ForeignKey("RecipeId")]
public int RecipeId { get; private set; }
/// <summary>
/// Сущность "Рецепт"
/// </summary>
public virtual Recipe Recipe { get; private set; } = new();
/// <summary>
/// Создать сущность
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
public static Disease? Create(HospitalDatabase context, DiseaseBindingModel model)
{
if (model == null)
{
return null;
}
return new Disease()
{
Id = model.Id,
Name = model.Name,
Symptoms = model.Symptoms,
RecipeId = model.RecipeId,
Recipe = context.Recipes
.First(x => x.Id == model.RecipeId)
};
}
/// <summary>
/// Изменить сущность
/// </summary>
/// <param name="model"></param>
public void Update(DiseaseBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
Symptoms = model.Symptoms;
}
/// <summary>
/// Получить модель представления
/// </summary>
public DiseaseViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Symptoms = Symptoms,
RecipeId = RecipeId
};
}
}

View File

@ -0,0 +1,102 @@
using HospitalContracts.BindingModels;
using HospitalContracts.ViewModels;
using HospitalDataModels.Enums;
using HospitalDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Сущность "Доктор"
/// </summary>
public class Doctor : IDoctorModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// ФИО доктора
/// </summary>
[Required]
[MaxLength(100)]
public string FullName { get; private set; } = string.Empty;
/// <summary>
/// Должность доктора
/// </summary>
[Required]
public DoctorPost Post { get; private set; }
/// <summary>
/// Логин (электронная почта)
/// </summary>
[Required]
[MaxLength(30)]
public string Email { get; private set; } = string.Empty;
/// <summary>
/// Пароль
/// </summary>
[Required]
[MaxLength(30)]
public string Password { get; private set; } = string.Empty;
/// <summary>
/// Создать сущность
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Doctor? Create(DoctorBindingModel model)
{
if (model == null)
{
return null;
}
return new Doctor()
{
Id = model.Id,
FullName = model.FullName,
Post = model.Post,
Email = model.Email,
Password = model.Password
};
}
/// <summary>
/// Изменить сущность
/// </summary>
/// <param name="model"></param>
public void Update(DoctorBindingModel model)
{
if (model == null)
{
return;
}
FullName = model.FullName;
Post = model.Post;
Email = model.Email;
Password = model.Password;
}
/// <summary>
/// Получить модель представления
/// </summary>
public DoctorViewModel GetViewModel => new()
{
Id = Id,
FullName = FullName,
Post = Post,
Email = Email,
Password = Password
};
}
}

View File

@ -0,0 +1,81 @@
using HospitalContracts.BindingModels;
using HospitalContracts.ViewModels;
using HospitalDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Сущность "Лекарство"
/// </summary>
public class Medicine : IMedicineModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Название лекарства
/// </summary>
[Required]
[MaxLength(30)]
public string Name { get; private set; } = string.Empty;
/// <summary>
/// Описание лекарства
/// </summary>
[MaxLength(100)]
public string? Description { get; private set; }
/// <summary>
/// Создать сущность
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Medicine? Create(MedicineBindingModel model)
{
if (model == null)
{
return null;
}
return new Medicine()
{
Id = model.Id,
Name = model.Name,
Description = model.Description
};
}
/// <summary>
/// Изменить сущность
/// </summary>
/// <param name="model"></param>
public void Update(MedicineBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
Description = model.Description;
}
/// <summary>
/// Получить модель представления
/// </summary>
public MedicineViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Description = Description
};
}
}

View File

@ -0,0 +1,231 @@
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;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Сущность "Пациент"
/// </summary>
public class Patient : IPatientModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// ФИО пациента
/// </summary>
[Required]
[MaxLength(100)]
public string FullName { get; private set; } = string.Empty;
/// <summary>
/// Дата рождения пациента
/// </summary>
[Required]
public DateTime BirthDate { get; private set; }
/// <summary>
/// Номер телефона пациента
/// </summary>
[Required]
[MaxLength(16)]
public string Phone { get; private set; } = string.Empty;
/// <summary>
/// Идентификатор лечащего врача
/// </summary>
[ForeignKey("DoctorId")]
public int DoctorId { get; private set; }
/// <summary>
/// Лечащий врач
/// </summary>
public virtual Doctor Doctor { get; private set; } = new();
/// <summary>
/// Связь с таблицей связи для сущностей "Пациент" и "Рецепт"
/// </summary>
[ForeignKey("PatientId")]
public virtual List<PatientRecipe> Recipes { get; set; } = new();
/// <summary>
/// Список рецептов пациента
/// </summary>
private Dictionary<int, IRecipeModel>? _patientRecipes = null;
/// <summary>
/// Список рецептов пациента
/// </summary>
[NotMapped]
public Dictionary<int, IRecipeModel> PatientRecipes
{
get
{
if (_patientRecipes == null)
{
_patientRecipes = Recipes
.ToDictionary(recPR => recPR.RecipeId, recPR => (recPR.Recipe as IRecipeModel));
}
return _patientRecipes;
}
}
/// <summary>
/// Связь с таблицей связи для сущностей "Пациент" и "Процедура"
/// </summary>
[ForeignKey("PatientId")]
public virtual List<PatientProcedure> Procedures { get; set; } = new();
/// <summary>
/// Список процедур пациента
/// </summary>
private Dictionary<int, IProcedureModel>? _patientProcedures = null;
/// <summary>
/// Список процедур пациента
/// </summary>
[NotMapped]
public Dictionary<int, IProcedureModel> PatientProcedures
{
get
{
if (_patientProcedures == null)
{
_patientProcedures = Procedures
.ToDictionary(recPP => recPP.ProcedureId, recPP => (recPP.Procedure as IProcedureModel));
}
return _patientProcedures;
}
}
/// <summary>
/// Cоздать сущность
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
public static Patient? Create(HospitalDatabase context, PatientBindingModel model)
{
if (model == null)
{
return null;
}
return new Patient()
{
Id = model.Id,
FullName = model.FullName,
BirthDate = model.BirthDate,
Phone = model.Phone,
DoctorId = model.DoctorId,
Doctor = context.Doctors
.First(x => x.Id == model.DoctorId),
Recipes = model.PatientRecipes.Select(x => new PatientRecipe
{
Recipe = context.Recipes.First(y => y.Id == x.Key)
}).ToList(),
Procedures = model.PatientProcedures.Select(x => new PatientProcedure
{
Procedure = context.Procedures.First(y => y.Id == x.Key)
}).ToList()
};
}
/// <summary>
/// Изменить сущность
/// </summary>
/// <param name="model"></param>
public void Update(PatientBindingModel model)
{
if (model == null)
{
return;
}
FullName = model.FullName;
BirthDate = model.BirthDate;
Phone = model.Phone;
}
/// <summary>
/// Получить модель представления
/// </summary>
public PatientViewModel GetViewModel => new()
{
Id = Id,
FullName = FullName,
BirthDate = BirthDate,
Phone = Phone,
DoctorId = DoctorId,
DoctorFullName = Doctor.FullName,
PatientRecipes = PatientRecipes,
PatientProcedures = PatientProcedures
};
/// <summary>
/// Обновить связи с рецептами
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
public void UpdateRecipes(HospitalDatabase context, PatientBindingModel model)
{
var patientRecipes = context.PatientRecipes.Where(rec => rec.PatientId == model.Id).ToList();
if (patientRecipes != null && patientRecipes.Count > 0)
{
// Удаление рецептов, не относящихся к пациенту
context.PatientRecipes.RemoveRange(patientRecipes.Where(rec => !model.PatientRecipes.ContainsKey(rec.RecipeId)));
context.SaveChanges();
}
var patient = context.Patients.First(x => x.Id == Id);
foreach (var pr in model.PatientRecipes)
{
context.PatientRecipes.Add(new PatientRecipe
{
Patient = patient,
Recipe = context.Recipes.First(x => x.Id == pr.Key)
});
context.SaveChanges();
}
_patientRecipes = null;
}
/// <summary>
/// Обновить связи с процедурами
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
public void UpdateProcedures(HospitalDatabase context, PatientBindingModel model)
{
var patientProcedures = context.PatientProcedures.Where(rec => rec.PatientId == model.Id).ToList();
if (patientProcedures != null && patientProcedures.Count > 0)
{
// Удаление процедур, не относящихся к пациенту
context.PatientProcedures.RemoveRange(patientProcedures.Where(rec => !model.PatientProcedures.ContainsKey(rec.ProcedureId)));
context.SaveChanges();
}
var patient = context.Patients.First(x => x.Id == Id);
foreach (var pp in model.PatientProcedures)
{
context.PatientProcedures.Add(new PatientProcedure
{
Patient = patient,
Procedure = context.Procedures.First(x => x.Id == pp.Key)
});
context.SaveChanges();
}
_patientProcedures = null;
}
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Класс связи для сущностей "Пациент" и "Процедура"
/// </summary>
public class PatientProcedure
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Идентификатор пациента
/// </summary>
[Required]
public int PatientId { get; set; }
/// <summary>
/// Сущность "Пациент"
/// </summary>
public virtual Patient Patient { get; set; } = new();
/// <summary>
/// Идентификатор процедуры
/// </summary>
[Required]
public int ProcedureId { get; set; }
/// <summary>
/// Сущность "Процедура"
/// </summary>
public virtual Procedure Procedure { get; set; } = new();
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Класс связи для сущностей "Пациент" и "Рецепт"
/// </summary>
public class PatientRecipe
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Идентификатор пациента
/// </summary>
[Required]
public int PatientId { get; set; }
/// <summary>
/// Сущность "Пациент"
/// </summary>
public virtual Patient Patient { get; set; } = new();
/// <summary>
/// Идентификатор рецепта
/// </summary>
[Required]
public int RecipeId { get; set; }
/// <summary>
/// Сущность "Рецепт"
/// </summary>
public virtual Recipe Recipe { get; set; } = new();
}
}

View File

@ -0,0 +1,144 @@
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;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Сущность "Процедура"
/// </summary>
public class Procedure : IProcedureModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Название процедуры
/// </summary>
[Required]
[MaxLength(30)]
public string Name { get; private set; } = string.Empty;
/// <summary>
/// Описание процедуры
/// </summary>
[MaxLength(100)]
public string? Description { get; private set; }
/// <summary>
/// Связь с таблицей связи для сущностей "Процедура" и "Лекарство"
/// </summary>
[ForeignKey("ProcedureId")]
public virtual List<ProcedureMedicine> Medicines { get; set; } = new();
/// <summary>
/// Список лекарств для процедуры
/// </summary>
private Dictionary<int, IMedicineModel>? _procedureMedicines = null;
/// <summary>
/// Список лекарств для процедуры
/// </summary>
[NotMapped]
public Dictionary<int, IMedicineModel> ProcedureMedicines
{
get
{
if (_procedureMedicines == null)
{
_procedureMedicines = Medicines
.ToDictionary(recPM => recPM.MedicineId, recPM => (recPM.Medicine as IMedicineModel));
}
return _procedureMedicines;
}
}
/// <summary>
/// Создать сущность
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
public static Procedure? Create(HospitalDatabase context, ProcedureBindingModel model)
{
if (model == null)
{
return null;
}
return new Procedure()
{
Id = model.Id,
Name = model.Name,
Description = model.Description,
Medicines = model.ProcedureMedicines.Select(x => new ProcedureMedicine
{
Medicine = context.Medicines.First(y => y.Id == x.Key)
}).ToList()
};
}
/// <summary>
/// Изменить сущность
/// </summary>
/// <param name="model"></param>
public void Update(ProcedureBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
Description = model.Description;
}
/// <summary>
/// Получить модель представления
/// </summary>
public ProcedureViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Description = Description,
ProcedureMedicines = ProcedureMedicines
};
/// <summary>
/// Обновить связи с лекарствами
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
public void UpdateMedicines(HospitalDatabase context, ProcedureBindingModel model)
{
var procedureMedicines = context.ProcedureMedicines.Where(rec => rec.ProcedureId == model.Id).ToList();
if (procedureMedicines != null && procedureMedicines.Count > 0)
{
// Удаление лекарств, не относящихся к процедуре
context.ProcedureMedicines.RemoveRange(procedureMedicines.Where(rec => !model.ProcedureMedicines.ContainsKey(rec.MedicineId)));
context.SaveChanges();
}
var procedure = context.Procedures.First(x => x.Id == Id);
foreach (var pm in model.ProcedureMedicines)
{
context.ProcedureMedicines.Add(new ProcedureMedicine
{
Procedure = procedure,
Medicine = context.Medicines.First(x => x.Id == pm.Key)
});
context.SaveChanges();
}
_procedureMedicines = null;
}
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Класс связи для сущностей "Процедура" и "Лекарство"
/// </summary>
public class ProcedureMedicine
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Идентификатор процедуры
/// </summary>
[Required]
public int ProcedureId { get; set; }
/// <summary>
/// Сущность "Процедура"
/// </summary>
public virtual Procedure Procedure { get; set; } = new();
/// <summary>
/// Идентификатор лекарства
/// </summary>
[Required]
public int MedicineId { get; set; }
/// <summary>
/// Сущность "Лекарство"
/// </summary>
public virtual Medicine Medicine { get; set; } = new();
}
}

View File

@ -0,0 +1,150 @@
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;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Сущность "Рецепт"
/// </summary>
public class Recipe : IRecipeModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Дата выписки рецепта
/// </summary>
[Required]
public DateTime IssueDate { get; private set; } = DateTime.Now;
/// <summary>
/// Идентификатор доктора
/// </summary>
[ForeignKey("DoctorId")]
public int DoctorId { get; private set; }
/// <summary>
/// Сущность "Доктор"
/// </summary>
public virtual Doctor Doctor { get; private set; } = new();
/// <summary>
/// Связь с таблицей связи для сущностей "Рецепт" и "Лекарство"
/// </summary>
[ForeignKey("RecipeId")]
public virtual List<RecipeMedicine> Medicines { get; set; } = new();
/// <summary>
/// Список лекарств в рецепте
/// </summary>
private Dictionary<int, IMedicineModel>? _recipeMedicines = null;
/// <summary>
/// Список лекарств в рецепте
/// </summary>
[NotMapped]
public Dictionary<int, IMedicineModel> RecipeMedicines
{
get
{
if (_recipeMedicines == null)
{
_recipeMedicines = Medicines
.ToDictionary(recRM => recRM.MedicineId, recRM => (recRM.Medicine as IMedicineModel));
}
return _recipeMedicines;
}
}
/// <summary>
/// Cоздать сущность
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
public static Recipe? Create(HospitalDatabase context, RecipeBindingModel model)
{
if (model == null)
{
return null;
}
return new Recipe()
{
Id = model.Id,
IssueDate = model.IssueDate,
DoctorId = model.DoctorId,
Doctor = context.Doctors
.First(x => x.Id == model.DoctorId),
Medicines = model.RecipeMedicines.Select(x => new RecipeMedicine
{
Medicine = context.Medicines.First(y => y.Id == x.Key)
}).ToList()
};
}
/// <summary>
/// Изменить сущность
/// </summary>
/// <param name="model"></param>
public void Update(RecipeBindingModel model)
{
if (model == null)
{
return;
}
IssueDate = model.IssueDate;
}
/// <summary>
/// Получить модель представления
/// </summary>
public RecipeViewModel GetViewModel => new()
{
Id = Id,
IssueDate = IssueDate,
DoctorId = DoctorId,
DoctorFullName = Doctor.FullName,
RecipeMedicines = RecipeMedicines
};
/// <summary>
/// Обновить связи с лекарствами
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
public void UpdateMedicines(HospitalDatabase context, RecipeBindingModel model)
{
var recipeMedicines = context.RecipeMedicines.Where(rec => rec.RecipeId == model.Id).ToList();
if (recipeMedicines != null && recipeMedicines.Count > 0)
{
// Удаление лекарств, не относящихся к рецепту
context.RecipeMedicines.RemoveRange(recipeMedicines.Where(rec => !model.RecipeMedicines.ContainsKey(rec.MedicineId)));
context.SaveChanges();
}
var recipe = context.Recipes.First(x => x.Id == Id);
foreach (var rm in model.RecipeMedicines)
{
context.RecipeMedicines.Add(new RecipeMedicine
{
Recipe = recipe,
Medicine = context.Medicines.First(x => x.Id == rm.Key)
});
context.SaveChanges();
}
_recipeMedicines = null;
}
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDatabaseImplement.Models
{
/// <summary>
/// Класс связи для сущностей "Рецепт" и "Лекарство"
/// </summary>
public class RecipeMedicine
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Идентификатор рецепта
/// </summary>
[Required]
public int RecipeId { get; set; }
/// <summary>
/// Сущность "Рецепт"
/// </summary>
public virtual Recipe Recipe { get; set; } = new();
/// <summary>
/// Идентификатор лекарства
/// </summary>
[Required]
public int MedicineId { get; set; }
/// <summary>
/// Сущность "Лекарство"
/// </summary>
public virtual Medicine Medicine { get; set; } = new();
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.