using RestaurantContracts.BindingModels; using RestaurantContracts.ViewModels; using RestaurantDataModels.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 RestaurantDatabaseImplement.Models { public class Component : IComponentModel { [Required] public string Name { get; private set; } = string.Empty; [Required] public int Price { get; private set; } [Required] public int Count { get; private set; } private Dictionary? _componentProviders = null; [NotMapped] public Dictionary ComponentProviders { get { if (_componentProviders == null) { _componentProviders = Providers.ToDictionary(recPC => recPC.ProviderId, recPC => (recPC.Provider as IProviderModel, recPC.Count, recPC.Date)); } return _componentProviders; } } [ForeignKey("ComponentId")] public virtual List Providers { get; set; } = new(); public int Id { get; private set; } [ForeignKey("ComponentId")] public virtual List ProductComponents { get; set; } = new(); public static Component? Create(RestaurantDatabase context, ComponentBindingModel? model) { if (model == null) { return null; } return new Component() { Id = model.Id, Name = model.Name, Price = model.Price, Count = model.Count, Providers = model.ComponentProviders.Select(x => new ComponentProvider { Provider = context.Providers.First(y => y.Id == x.Key), Count = x.Value.Item2, Date = x.Value.Item3 }).ToList() }; } public void Update(ComponentBindingModel? model) { Name = model.Name; Price = model.Price; Count = model.Count; } public ComponentViewModel GetViewModel => new() { Id = Id, Name = Name, Price = Price, Count = Count, ComponentProviders = ComponentProviders, }; public void UpdateComponents(RestaurantDatabase context, ComponentBindingModel model) { var ComponentProviders = context.ComponentProviders.Where(rec => rec.ComponentId == model.Id).ToList(); if (ComponentProviders != null && ComponentProviders.Count > 0) { // удалили те, которых нет в модели context.ComponentProviders.RemoveRange(ComponentProviders.Where(rec => !model.ComponentProviders.ContainsKey(rec.ProviderId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateComponent in ComponentProviders) { updateComponent.Count = model.ComponentProviders[updateComponent.ProviderId].Item2; model.ComponentProviders.Remove(updateComponent.ProviderId); } context.SaveChanges(); } var Component = context.Components.First(x => x.Id == Id); foreach (var pc in model.ComponentProviders) { context.ComponentProviders.Add(new ComponentProvider { Component = Component, Provider = context.Providers.First(x => x.Id == pc.Key), Count = pc.Value.Item2, Date = pc.Value.Item3 // ?????? }); context.SaveChanges(); } _componentProviders = null; } } }