using SoftwareInstallationDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; namespace SoftwareInstallationDatabaseImplement.Models { public class Software : IPackageModel { public int Id { get; set; } [Required] public string SoftwareName { get; set; } = string.Empty; [Required] public double Price { get; set; } private Dictionary? _SoftwareComponents = null; [NotMapped] public Dictionary SoftwareComponents { get { if (_SoftwareComponents == null) { _SoftwareComponents = Components .ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); } return _SoftwareComponents; } } [ForeignKey("SoftwareId")] public virtual List Components { get; set; } = new(); [ForeignKey("SoftwareId")] public virtual List Orders { get; set; } = new(); public static Software Create(SoftwareInstallationDataBase context, PackageBindingModel model) { return new Software() { Id = model.Id, SoftwareName = model.SoftwareName, Price = model.Price, Components = model.SoftwareComponents.Select(x => new PackageComponent { Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(PackageBindingModel model) { SoftwareName = model.SoftwareName; Price = model.Price; } public PackageViewModel GetViewModel => new() { Id = Id, SoftwareName = SoftwareName, Price = Price, SoftwareComponents = SoftwareComponents }; public void UpdateComponents(SoftwareInstallationDataBase context, PackageBindingModel model) { var SoftwareComponents = context.SoftwareComponents.Where(rec => rec.SoftwareId == model.Id).ToList(); if (SoftwareComponents != null && SoftwareComponents.Count > 0) { context.SoftwareComponents.RemoveRange(SoftwareComponents.Where(rec => !model.SoftwareComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); foreach (var updateComponent in SoftwareComponents) { updateComponent.Count = model.SoftwareComponents[updateComponent.ComponentId].Item2; model.SoftwareComponents.Remove(updateComponent.ComponentId); } context.SaveChanges(); } var Software = context.Softwares.First(x => x.Id == Id); foreach (var pc in model.SoftwareComponents) { context.SoftwareComponents.Add(new PackageComponent { Software = Software, Component = context.Components.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _SoftwareComponents = null; } } }