using HotelContracts.BindingModels; using HotelContracts.ViewModels; using HotelDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HotelDataBaseImplement.Models { public class MealPlan : IMealPlanModel { [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 Organiser Organiser { get; set; } [ForeignKey("MealPlanId")] public virtual List Rooms { get; set; } [ForeignKey("MealPlanId")] public virtual List Members { get; set; } private Dictionary _mealPlanMembers = null; public Dictionary MealPlanMembers { get { if (_mealPlanMembers == null) { _mealPlanMembers = Members.ToDictionary(recPC => recPC.MemberId, recPC => (recPC.Member as IMemberModel)); } return _mealPlanMembers; } } public static MealPlan Create(HotelDataBase context, MealPlanBindingModel model) { return new MealPlan() { Id = model.Id, MealPlanName = model.MealPlanName, MealPlanPrice = model.MealPlanPrice, OrganiserId = model.OrganiserId, Members = model.MealPlanMembers.Select(x => new MealPlanMember { Member = context.Members.First(y => y.Id == x.Key), }).ToList() }; } public void Update(MealPlanBindingModel model) { MealPlanName = model.MealPlanName; MealPlanPrice = model.MealPlanPrice; OrganiserId = model.OrganiserId; } public MealPlanViewModel GetViewModel => new() { Id = Id, MealPlanName = MealPlanName, MealPlanPrice = MealPlanPrice, OrganiserId=OrganiserId, MealPlanMembers = MealPlanMembers }; public void UpdateMembers(HotelDataBase context, MealPlanBindingModel 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 MealPlanMember { MealPlan = mealPlan, Member = context.Members.First(x => x.Id == cm.Key) }); context.SaveChanges(); } _mealPlanMembers = null; } } }