using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.ViewModels; using AircraftPlantDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AircraftPlantDatabaseImplement.Models { public class Plane : IPlaneModel { public int Id { get; set; } [Required] public string PlaneName { get; set; } = string.Empty; [Required] public double Price { get; set; } private Dictionary? _planeComponents = null; [NotMapped] public Dictionary PlaneComponents { get { if (_planeComponents == null) { _planeComponents = Components .ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); } return _planeComponents; } } [ForeignKey("PlaneId")] public virtual List Components { get; set; } = new(); [ForeignKey("PlaneId")] public virtual List Orders { get; set; } = new(); public static Plane Create(AircraftPlantDatabase context, PlaneBindingModel model) { return new Plane() { Id = model.Id, PlaneName = model.PlaneName, Price = model.Price, Components = model.PlaneComponents.Select(x => new PlaneComponent { Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(PlaneBindingModel model) { PlaneName = model.PlaneName; Price = model.Price; } public PlaneViewModel GetViewModel => new() { Id = Id, PlaneName = PlaneName, Price = Price, PlaneComponents = PlaneComponents }; public void UpdateComponents(AircraftPlantDatabase context, PlaneBindingModel model) { var planeComponents = context.PlaneComponents.Where(rec => rec.PlaneId == model.Id).ToList(); if (planeComponents != null && planeComponents.Count > 0) { // Удаление компонентов, которых нет в модели context.PlaneComponents.RemoveRange(planeComponents.Where(rec => !model.PlaneComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); // Обновление количества у существующих записей foreach (var updateComponent in planeComponents) { updateComponent.Count = model.PlaneComponents[updateComponent.ComponentId].Item2; model.PlaneComponents.Remove(updateComponent.ComponentId); } context.SaveChanges(); } var plane = context.Planes.First(x => x.Id == Id); foreach (var pc in model.PlaneComponents) { context.PlaneComponents.Add(new PlaneComponent { Plane = plane, Component = context.Components.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _planeComponents = null; } } }