using BankContracts.BindingModels; using BankContracts.ViewModels; using BankDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BankDataBaseImplement.Models { public class Additions : IAdditionsModel { [Required] public string MealPlanName { get; set; } = string.Empty; [Required] public double MealPlanPrice { get; set; } public int OrganiserId { get; private set; } public int Id { get; private set; } public virtual Clerc Organiser { get; set; } [ForeignKey("MealPlanId")] public virtual List<Room> Rooms { get; set; } [ForeignKey("MealPlanId")] public virtual List<AdditionsMember> Members { get; set; } private Dictionary<int, IMemberModel> _mealPlanMembers = null; public Dictionary<int, IMemberModel> MealPlanMembers { get { if (_mealPlanMembers == null) { _mealPlanMembers = Members.ToDictionary(recPC => recPC.MemberId, recPC => (recPC.Member as IMemberModel)); } return _mealPlanMembers; } } public static Additions Create(BankDataBase context, AdditionsBindingModel model) { return new Additions() { Id = model.Id, MealPlanName = model.MealPlanName, MealPlanPrice = model.MealPlanPrice, Members = model.MealPlanMembers.Select(x => new AdditionsMember { Member = context.Members.First(y => y.Id == x.Key), }).ToList() }; } public void Update(AdditionsBindingModel model) { MealPlanName = model.MealPlanName; MealPlanPrice = model.MealPlanPrice; } public AdditionsPlanViewModel GetViewModel => new() { Id = Id, MealPlanName = MealPlanName, MealPlanPrice = MealPlanPrice, MealPlanMembers = MealPlanMembers }; public void UpdateMembers(BankDataBase context, AdditionsBindingModel model) { var mealPlanMembers = context.MealPlanMembers.Where(rec => rec.MealPlanId == model.Id).ToList(); if (mealPlanMembers != null) { context.MealPlanMembers.RemoveRange(mealPlanMembers.Where(rec => !model.MealPlanMembers.ContainsKey(rec.MemberId))); context.SaveChanges(); } var mealPlan = context.MealPlans.First(x => x.Id == Id); foreach (var cm in model.MealPlanMembers) { context.MealPlanMembers.Add(new AdditionsMember { MealPlan = mealPlan, Member = context.Members.First(x => x.Id == cm.Key) }); context.SaveChanges(); } _mealPlanMembers = null; } } }