using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using TravelAgencyContracts.BindingModels; using TravelAgencyContracts.ViewModels; using TravelAgencyDataModels.Models; namespace TravelAgencyDatabaseImplement.Models { public class Excursion : IExcursionModel { public int Id { get; set; } [Required] public string ExcursionName { get; set; } = string.Empty; public string ExcursionDescription { get; set; } = string.Empty; [Required] public double Price { get; set; } [Required] public int UserId { get; set; } [DeleteBehavior(DeleteBehavior.Restrict)] public virtual User User { get; set; } [Required] public int PlaceId { get; set; } public virtual Place Place { get; set; } private Dictionary? _excursionTours = null; [NotMapped] public Dictionary ExcursionTours { get { if (_excursionTours == null) { _excursionTours = Tours .ToDictionary(recPC => recPC.TourId, recPC => recPC.Tour as ITourModel); } return _excursionTours; } } [ForeignKey("ExcursionId")] public virtual List Tours { get; set; } = new(); public static Excursion? Create(TravelAgencyDatabase context, ExcursionBindingModel? model) { if (model == null) { return null; } return new Excursion() { Id = model.Id, ExcursionName = model.ExcursionName, ExcursionDescription = model.ExcursionDescription, Price = model.Price, UserId = model.UserId, PlaceId = model.PlaceId, Place = context.Places .First(x => x.Id == model.PlaceId), Tours = model.ExcursionTours.Select(x => new ExcursionTour { Tour = context.Tours.First(y => y.Id == x.Key) }).ToList() }; } public void Update(ExcursionBindingModel? model) { if (model == null) { return; } using var context = new TravelAgencyDatabase(); ExcursionName = model.ExcursionName; ExcursionDescription = model.ExcursionDescription; Price = model.Price; PlaceId = model.PlaceId; Place = context.Places .First(x => x.Id == model.PlaceId); } public ExcursionViewModel GetViewModel => new() { Id = Id, ExcursionName = ExcursionName, ExcursionDescription = ExcursionDescription, Price = Price, UserId = UserId, PlaceId = PlaceId, PlaceName = Place?.PlaceName, ExcursionTours = ExcursionTours }; public void UpdateTours(TravelAgencyDatabase context, ExcursionBindingModel model) { var excursionTours = context.ExcursionTours.Where(rec => rec.ExcursionId == model.Id).ToList(); if (excursionTours != null && excursionTours.Count > 0) { // удалили те, которых нет в модели context.ExcursionTours.RemoveRange(excursionTours.Where(rec => !model.ExcursionTours.ContainsKey(rec.TourId))); context.SaveChanges(); } var excursion = context.Excursions.First(x => x.Id == Id); foreach (var et in model.ExcursionTours) { if (excursionTours!.Any(x => x.TourId == et.Key)) { continue; } context.ExcursionTours.Add(new ExcursionTour { Excursion = excursion, Tour = context.Tours.First(x => x.Id == et.Key) }); context.SaveChanges(); } _excursionTours = null; } } }