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 { /// /// Сущность "Рецепт" /// public class Recipe : IRecipeModel { /// /// Идентификатор /// public int Id { get; private set; } /// /// Дата выписки рецепта /// [Required] public DateTime IssueDate { get; private set; } = DateTime.Now; /// /// Идентификатор доктора /// [ForeignKey("DoctorId")] public int DoctorId { get; private set; } /// /// Сущность "Доктор" /// public virtual Doctor Doctor { get; private set; } = new(); /// /// Связь с таблицей связи для сущностей "Рецепт" и "Лекарство" /// [ForeignKey("RecipeId")] public virtual List Medicines { get; set; } = new(); /// /// Список лекарств в рецепте /// private Dictionary? _recipeMedicines = null; /// /// Список лекарств в рецепте /// [NotMapped] public Dictionary RecipeMedicines { get { if (_recipeMedicines == null) { _recipeMedicines = Medicines .ToDictionary(recRM => recRM.MedicineId, recRM => (recRM.Medicine as IMedicineModel)); } return _recipeMedicines; } } /// /// Cоздать сущность /// /// /// /// 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() }; } /// /// Изменить сущность /// /// public void Update(RecipeBindingModel model) { if (model == null) { return; } IssueDate = model.IssueDate; } /// /// Получить модель представления /// public RecipeViewModel GetViewModel => new() { Id = Id, IssueDate = IssueDate, DoctorId = DoctorId, DoctorFullName = Doctor.FullName, RecipeMedicines = RecipeMedicines }; /// /// Обновить связи с лекарствами /// /// /// 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) { if (recipeMedicines!.Any(x => x.MedicineId == rm.Key)) { continue; } context.RecipeMedicines.Add(new RecipeMedicine { Recipe = recipe, Medicine = context.Medicines.First(x => x.Id == rm.Key) }); context.SaveChanges(); } _recipeMedicines = null; } } }