using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using TravelAgencyContracts.BindingModels; using TravelAgencyContracts.ViewModels; using TravelAgencyDataModels.Models; using Microsoft.EntityFrameworkCore; namespace TravelAgencyDatabaseImplement.Models { public class ExcursionGroup : IExcursionGroupModel { public int Id { get; set; } [Required] public string ExcursionGroupName { get; set; } = string.Empty; [Required] public int ParticipantsAmount { get; set; } [Required] public int UserId { get; set; } [DeleteBehavior(DeleteBehavior.Restrict)] public virtual User User { get; set; } [Required] public int GuideId { get; set; } public virtual Guide Guide { get; set; } private Dictionary? _excursionGroupTours = null; [NotMapped] public Dictionary ExcursionGroupTours { get { if (_excursionGroupTours == null) { _excursionGroupTours = Tours .ToDictionary(recPC => recPC.TourId, recPC => recPC.Tour as ITourModel); } return _excursionGroupTours; } } [ForeignKey("ExcursionGroupId")] public virtual List Tours { get; set; } = new(); public static ExcursionGroup? Create(TravelAgencyDatabase context, ExcursionGroupBindingModel? model) { if (model == null) { return null; } return new ExcursionGroup() { Id = model.Id, ExcursionGroupName = model.ExcursionGroupName, ParticipantsAmount = model.ParticipantsAmount, UserId = model.UserId, GuideId = model.GuideId, Guide = context.Guides .First(x => x.Id == model.GuideId), Tours = model.ExcursionGroupTours.Select(x => new ExcursionGroupTour { Tour = context.Tours.First(y => y.Id == x.Key) }).ToList() }; } public void Update(ExcursionGroupBindingModel? model) { if (model == null) { return; } ExcursionGroupName = model.ExcursionGroupName; ParticipantsAmount = model.ParticipantsAmount; } public ExcursionGroupViewModel GetViewModel => new() { Id = Id, ExcursionGroupName = ExcursionGroupName, ParticipantsAmount = ParticipantsAmount, UserId = UserId, GuideId = GuideId, GuideFIO = Guide.GuideFIO, ExcursionGroupTours = ExcursionGroupTours }; public void UpdateTours(TravelAgencyDatabase context, ExcursionGroupBindingModel model) { var excursionGroupTours = context.ExcursionGroupTours.Where(rec => rec.ExcursionGroupId == model.Id).ToList(); if (excursionGroupTours != null && excursionGroupTours.Count > 0) { // удалили те, которых нет в модели context.ExcursionGroupTours.RemoveRange(excursionGroupTours.Where(rec => !model.ExcursionGroupTours.ContainsKey(rec.TourId))); context.SaveChanges(); } var excursionGroup = context.ExcursionGroups.First(x => x.Id == Id); foreach (var et in model.ExcursionGroupTours) { context.ExcursionGroupTours.Add(new ExcursionGroupTour { ExcursionGroup = excursionGroup, Tour = context.Tours.First(x => x.Id == et.Key) }); context.SaveChanges(); } _excursionGroupTours = null; } } }