using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.ViewModels; using PrecastConcretePlantDatabaseImplement; using PrecastConcretePlantDatabaseImplement.Models; using PrecastConcretePlantDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public class Shop : IShopModel { public int Id { get; set; } [Required] public string ShopName { get; set; } = string.Empty; [Required] public string Address { get; set; } = string.Empty; [Required] public DateTime DateOpening { get; set; } [Required] public int Capacity { get; set; } private Dictionary? _shopReinforceds = null; [NotMapped] public Dictionary ShopReinforceds { get { if (_shopReinforceds == null) { _shopReinforceds = Reinforceds.ToDictionary(rec => rec.ReinforcedId, rec => (rec.Reinforced as IReinforcedModel, rec.Count)); } return _shopReinforceds; } } [ForeignKey("ShopId")] public virtual List Reinforceds { get; set; } = new(); public static Shop Create(PrecastConcretePlantDatabase context, ShopBindingModel model) { return new Shop() { Id = model.Id, ShopName = model.ShopName, Address = model.Address, DateOpening = model.DateOpening, Capacity = model.Capacity, Reinforceds = model.ShopReinforceds.Select(x => new ShopReinforced { Reinforced = context.Reinforceds.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(ShopBindingModel model) { ShopName = model.ShopName; Address = model.Address; DateOpening = model.DateOpening; Capacity = model.Capacity; } public ShopViewModel GetViewModel => new() { Id = Id, ShopName = ShopName, Address = Address, DateOpening = DateOpening, Capacity = Capacity, ShopReinforceds = ShopReinforceds }; public void UpdateTravels(PrecastConcretePlantDatabase context, ShopBindingModel model) { var shopReinforceds = context.ShopReinforceds.Where(rec => rec.ShopId == model.Id).ToList(); if (shopReinforceds != null && shopReinforceds.Count > 0) { // удалили те, которых нет в модели context.ShopReinforceds.RemoveRange(shopReinforceds.Where(rec => !model.ShopReinforceds.ContainsKey(rec.ReinforcedId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateTravel in shopReinforceds) { updateTravel.Count = model.ShopReinforceds[updateTravel.ReinforcedId].Item2; model.ShopReinforceds.Remove(updateTravel.ReinforcedId); } context.SaveChanges(); } var shop = context.Shops.First(x => x.Id == Id); foreach (var st in model.ShopReinforceds) { context.ShopReinforceds.Add(new ShopReinforced { Shop = shop, Reinforced = context.Reinforceds.First(x => x.Id == st.Key), Count = st.Value.Item2 }); context.SaveChanges(); } _shopReinforceds = null; } }