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

93 lines
3.0 KiB
C#
Raw Normal View History

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 Procedure : IProcedureModel
{
public int Id { get; set; }
[Required]
public int UserId { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public string Comment { get; set; } = string.Empty;
private Dictionary<int, IRecipeModel>? _procedureRecipes = null;
[ForeignKey("ProcedureId")]
public virtual List<ProcedureRecipe> Recipes { get; set; } = new();
[NotMapped]
public Dictionary<int, IRecipeModel> ProcedureRecipes
{
get
{
if(_procedureRecipes == null)
{
_procedureRecipes = Recipes.ToDictionary(recPC => recPC.RecipeId, recPC => (recPC.Recipe as IRecipeModel));
}
return _procedureRecipes;
}
}
public static Procedure Create(PolyclinicDatabase database, ProcedureBindingModel bindingModel)
{
return new Procedure()
{
Id = bindingModel.Id,
UserId = bindingModel.UserId,
Name = bindingModel.Name,
Comment = bindingModel.Comment,
Recipes = bindingModel.ProcedureRecipes.Select(x => new ProcedureRecipe
{
Recipe = database.Recipes.First(y => y.Id == x.Key)
}).ToList()
};
}
public void Update(ProcedureBindingModel bindingModel)
{
Name = bindingModel.Name;
Comment = bindingModel.Comment;
}
public ProcedureViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
UserId = UserId,
Comment = Comment,
};
public void UpdateRecipes(PolyclinicDatabase database, ProcedureBindingModel bindingModel)
{
var ProcedureRecipes = database.ProcedureRecipes.Where(x => x.ProcedureId == bindingModel.Id).ToList();
if(ProcedureRecipes != null)
{
// удалили те, которых нет в модели
database.ProcedureRecipes.RemoveRange(ProcedureRecipes.Where(rec => !bindingModel.ProcedureRecipes.ContainsKey(rec.RecipeId)));
database.SaveChanges();
}
var Procedure = database.Procedures.First(x => x.Id == bindingModel.Id);
foreach (var pc in bindingModel.ProcedureRecipes)
{
database.ProcedureRecipes.Add(new ProcedureRecipe
{
Procedure = Procedure,
Recipe = database.Recipes.First(x => x.Id == pc.Key)
});
}
_procedureRecipes = null;
}
}
}