using JewelryStoreDataModels.Models; using JewelryStoreContracts.ViewModels; using JewelryStoreContracts.BindingModels; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; namespace JewelryStoreDatabaseImplement.Models { [DataContract] public class Jewel : IJewelModel { [DataMember] public int Id { get; set; } [Required] [DataMember] public string JewelName { get; set; } = string.Empty; [Required] [DataMember] public double Price { get; set; } private Dictionary? _jewelComponents = null; [NotMapped] [DataMember] public Dictionary JewelComponents { get { if (_jewelComponents == null) { _jewelComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); } return _jewelComponents; } } [ForeignKey("JewelId")] public virtual List Components { get; set; } = new(); [ForeignKey("JewelId")] public virtual List Orders { get; set; } = new(); public static Jewel Create(JewelryStoreDataBase context, JewelBindingModel model) { return new Jewel() { Id = model.Id, JewelName = model.JewelName, Price = model.Price, Components = model.JewelComponents.Select(x => new JewelComponent { Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(JewelBindingModel model) { JewelName = model.JewelName; Price = model.Price; } public JewelViewModel GetViewModel => new() { Id = Id, JewelName = JewelName, Price = Price, JewelComponents = JewelComponents }; public void UpdateComponents(JewelryStoreDataBase context, JewelBindingModel model) { var jewelComponents = context.JewelComponents.Where(rec => rec.JewelId == model.Id).ToList(); if (jewelComponents != null && jewelComponents.Count > 0) { // удалили те, которых нет в модели context.JewelComponents.RemoveRange(jewelComponents.Where(rec => !model.JewelComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateComponent in jewelComponents) { updateComponent.Count = model.JewelComponents[updateComponent.ComponentId].Item2; model.JewelComponents.Remove(updateComponent.ComponentId); } context.SaveChanges(); } var jewel = context.Jewels.First(x => x.Id == Id); foreach (var pc in model.JewelComponents) { context.JewelComponents.Add(new JewelComponent { Jewel = jewel, Component = context.Components.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _jewelComponents = null; } } }