CourseWork_Hotel/Hotel/HotelDataBaseImplement/Models/MealPlan.cs

92 lines
3.0 KiB
C#
Raw Normal View History

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<MealPlanMember> 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 MealPlan Create(HotelDataBase context, MealPlanBindingModel model)
{
return new MealPlan()
{
Id = model.Id,
MealPlanName = model.MealPlanName,
MealPlanPrice = model.MealPlanPrice,
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;
}
public MealPlanViewModel GetViewModel => new()
{
Id = Id,
MealPlanName = MealPlanName,
MealPlanPrice = MealPlanPrice,
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;
}
}
}