using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.ViewModels; using PrecastConcretePlantDataModels.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 PrecastConcretePlantDatabaseImplement.Models { public class Shop : IShopModel { public int Id { get; set; } [Required] public string Name { get; set; } = string.Empty; [Required] public string Address { get; set; } = string.Empty; [Required] public DateTime DateOpening { get; set; } [Required] public int ReinforcedMaxCount { get; set; } private Dictionary? _shopReinforcedies = null; [NotMapped] public Dictionary ShopReinforcedies { get { if (_shopReinforcedies == null) { _shopReinforcedies = Reinforcedies.ToDictionary(recST => recST.ReinforcedId, recST => (recST.Reinforced as IReinforcedModel, recST.Count)); } return _shopReinforcedies; } } [ForeignKey("ShopId")] public virtual List Reinforcedies { get; set; } = new(); public static Shop Create(PrecastConcretePlantDataBase context, ShopBindingModel model) { return new Shop() { Id = model.Id, Name = model.Name, Address = model.Address, DateOpening = model.DateOpening, ReinforcedMaxCount = model.ReinforcedMaxCount, Reinforcedies = model.ShopReinforcedies.Select(x => new ShopReinforced { Reinforced = context.Reinforcedies.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(ShopBindingModel model) { Name = model.Name; Address = model.Address; DateOpening = model.DateOpening; ReinforcedMaxCount = model.ReinforcedMaxCount; } public ShopViewModel GetViewModel => new() { Id = Id, Name = Name, Address = Address, DateOpening = DateOpening, ReinforcedMaxCount = ReinforcedMaxCount, ShopReinforcedies = ShopReinforcedies }; public void UpdateReinforcedies(PrecastConcretePlantDataBase context, ShopBindingModel model) { var shopReinforcedies = context.ShopReinforcedies.Where(rec => rec.ShopId == model.Id).ToList(); if (shopReinforcedies != null && shopReinforcedies.Count > 0) { context.ShopReinforcedies.RemoveRange(shopReinforcedies.Where(rec => !model.ShopReinforcedies.ContainsKey(rec.ReinforcedId))); context.SaveChanges(); foreach (var updateReinforced in shopReinforcedies) { updateReinforced.Count = model.ShopReinforcedies[updateReinforced.ReinforcedId].Item2; model.ShopReinforcedies.Remove(updateReinforced.ReinforcedId); } context.SaveChanges(); } var shop = context.Shops.First(x => x.Id == Id); foreach (var st in model.ShopReinforcedies) { context.ShopReinforcedies.Add(new ShopReinforced { Shop = shop, Reinforced = context.Reinforcedies.First(x => x.Id == st.Key), Count = st.Value.Item2 }); context.SaveChanges(); } _shopReinforcedies = null; } } }