using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.ViewModels; using FurnitureAssemblyDataModels.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 FurnitureAssemblyDatabaseImplement.Models { public class Furniture : IFurnitureModel { public int Id { get; set; } [Required] public string FurnitureName { get; set; } = string.Empty; [Required] public double Price { get; set; } private Dictionary? _furnitureComponents = null; [NotMapped] public Dictionary FurnitureComponents { get { if (_furnitureComponents == null) { _furnitureComponents = Components .ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); } return _furnitureComponents; } } [ForeignKey("FurnitureId")] public virtual List Components { get; set; } = new(); [ForeignKey("FurnitureId")] public virtual List Orders { get; set; } = new(); public static Furniture Create(FurnitureAssemblyDatabase context, FurnitureBindingModel model) { return new Furniture() { Id = model.Id, FurnitureName = model.FurnitureName, Price = model.Price, Components = model.FurnitureComponents.Select(x => new FurnitureComponent { Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(FurnitureBindingModel model) { FurnitureName = model.FurnitureName; Price = model.Price; } public FurnitureViewModel GetViewModel => new() { Id = Id, FurnitureName = FurnitureName, Price = Price, FurnitureComponents = FurnitureComponents }; public void UpdateComponents(FurnitureAssemblyDatabase context, FurnitureBindingModel model) { var furnitureComponents = context.FurnitureComponents.Where(rec => rec.FurnitureId == model.Id).ToList(); if (furnitureComponents != null && furnitureComponents.Count > 0) { // удалили те, которых нет в модели context.FurnitureComponents.RemoveRange(furnitureComponents.Where(rec => !model.FurnitureComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateComponent in furnitureComponents) { updateComponent.Count = model.FurnitureComponents[updateComponent.ComponentId].Item2; model.FurnitureComponents.Remove(updateComponent.ComponentId); } context.SaveChanges(); } var furniture = context.Furnitures.First(x => x.Id == Id); foreach (var pc in model.FurnitureComponents) { context.FurnitureComponents.Add(new FurnitureComponent { Furniture = furniture, Component = context.Components.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _furnitureComponents = null; } } }