using CarCenterContracts.BindingModels; using CarCenterContracts.ViewModels; using CarCenterDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CarCenterDataBaseImplement.Models { public class Inspection : IInspectionModel { public DateTime? InspectionDate { get; set; } public int AdministratorId { get; private set; } public int? EmployeeId { get; private set; } public int Id { get; private set; } public string InspectionName { get; set; } = string.Empty; public virtual Administrator Administrator { get; set; } public virtual Employee? Employee { get; set; } [ForeignKey("InspectionId")] public virtual List Cars { get; set; } private Dictionary _inspectionCars = null; [NotMapped] public Dictionary InspectionCars { get { if (_inspectionCars == null) { using var context = new CarCenterDataBase(); _inspectionCars = Cars .ToDictionary(x => x.CarId, x => (context.Cars .FirstOrDefault(y => y.Id == x.CarId)! as ICarModel)); } return _inspectionCars; } } public static InspectionCars Create(CarCenterDataBase context, InspectionBindingModel model) { return new Inspection() { Id = model.Id, EmployeeId = model.EmployeeId, AdministratorId = model.AdministratorId, InspectionName = model.InspectionName, Cars = model.InspectionCars.Select(x => new InspectionCar { Car = context.Cars.First(y => y.Id == x.Key), }).ToList() }; } public void Update(InspectionBindingModel model) { EmployeeId = model.EmployeeId; InspectionName = model.InspectionName; InspectionDate = model.InspectionDate; } public InspectionViewModel GetViewModel => new() { Id = Id, EmployeeId = EmployeeId, AdministratorId = AdministratorId, InspectionName = InspectionName, InspectionDate = InspectionDate, InspectionCars = InspectionCars, EmplFIO = Employee?.EmployeeFIO }; public void UpdateCars(CarCenterDataBase context, InspectionBindingModel model) { var inspectionCars = context.InspectionCars.Where(rec => rec.InspectionId == model.Id).ToList(); if (inspectionCars != null && inspectionCars.Any()) { context.InspectionCars.RemoveRange(inspectionCars.Where(rec => !model.InspectionCars.ContainsKey(rec.CarId))); context.SaveChanges(); foreach (var updateCar in inspectionCars) { model.InspectionCars.Remove(updateCar.CarId); } context.SaveChanges(); } var inspection = context.Inspections.First(x => x.Id == Id); foreach (var ic in model.InspectionCars) { context.InspectionCars.Add(new InspectionCar { Inspection = inspection, Car = context.Cars.First(x => x.Id == ic.Key) }); context.SaveChanges(); } _inspectionCars = null; } } }