using FishFactoryContracts.BindingModels; using FishFactoryContracts.ViewModels; using FishFactoryDataModel.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace FishFactoryDatabaseImplement.Models { public class Canned { public int Id { get; set; } [Required] public string CannedName { get; set; } = string.Empty; [Required] public double Price { get; set; } private Dictionary? _cannedComponents = null; [NotMapped] public Dictionary CannedComponents { get { if (_cannedComponents == null) { _cannedComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); } return _cannedComponents; } } [ForeignKey("CannedId")] public virtual List Components { get; set; } = new(); [ForeignKey("CannedId")] public virtual List Orders { get; set; } = new(); public static Canned Create(FishFactoryDatabase context, CannedBindingModel model) { return new Canned() { Id = model.Id, CannedName = model.CannedName, Price = model.Price, Components = model.CannedComponents.Select(x => new CannedComponent { Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(CannedBindingModel model) { CannedName = model.CannedName; Price = model.Price; } public CannedViewModel GetViewModel => new() { Id = Id, CannedName = CannedName, Price = Price, CannedComponents = CannedComponents }; public void UpdateComponents(FishFactoryDatabase context, CannedBindingModel model) { var cannedComponents = context.CannedComponents.Where(rec => rec.CannedId == model.Id).ToList(); if (cannedComponents != null && cannedComponents.Count > 0) { // удалили те, которых нет в модели context.CannedComponents.RemoveRange(cannedComponents.Where(rec => !model.CannedComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateComponent in cannedComponents) { updateComponent.Count = model.CannedComponents[updateComponent.ComponentId].Item2; model.CannedComponents.Remove(updateComponent.ComponentId); } context.SaveChanges(); } var canned = context.Canneds.First(x => x.Id == Id); foreach (var pc in model.CannedComponents) { context.CannedComponents.Add(new CannedComponent { Canned = canned, Component = context.Components.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _cannedComponents = null; } } }