using DinerContracts.BindingModels; using DinerContracts.ViewModels; using DinerDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; namespace DinerDataBaseImplement.Models { [DataContract] public class Snack : ISnackModel { [DataMember] public int Id { get; set; } [Required] [DataMember] public string SnackName { get; set; } = string.Empty; [Required] [DataMember] public double Price { get; set; } private Dictionary? _snackComponents = null; [NotMapped] [DataMember] public Dictionary SnackComponents { get { if (_snackComponents == null) { _snackComponents = Components .ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); } return _snackComponents; } } [ForeignKey("SnackId")] public virtual List Components { get; set; } = new(); [ForeignKey("SnackId")] public virtual List Orders { get; set; } = new(); public static Snack Create(DinerDatabase context, SnackBindingModel model) { return new Snack() { Id = model.Id, SnackName = model.SnackName, Price = model.Price, Components = model.SnackComponents.Select(x => new SnackComponent { Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(SnackBindingModel model) { SnackName = model.SnackName; Price = model.Price; } public SnackViewModel GetViewModel => new() { Id = Id, SnackName = SnackName, Price = Price, SnackComponents = SnackComponents }; public void UpdateComponents(DinerDatabase context, SnackBindingModel model) { var snackComponents = context.SnackComponents.Where(rec => rec.SnackId == model.Id).ToList(); if (snackComponents != null && snackComponents.Count > 0) { // удалили те, которых нет в модели context.SnackComponents.RemoveRange(snackComponents.Where(rec => !model.SnackComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateComponent in snackComponents) { updateComponent.Count = model.SnackComponents[updateComponent.ComponentId].Item2; model.SnackComponents.Remove(updateComponent.ComponentId); } context.SaveChanges(); } var snack = context.Snacks.First(x => x.Id == Id); foreach (var pc in model.SnackComponents) { context.SnackComponents.Add(new SnackComponent { Snack = snack, Component = context.Components.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _snackComponents = null; } } }