using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.ViewModels; using SecuritySystemDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace SecuritySystemDatabaseImplement.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 OpeningDate { get; set; } [Required] public int MaxSecuresCount { get; set; } [ForeignKey("ShopId")] public virtual List Secures { get; set; } = new(); private Dictionary? _shopSecures = null; [NotMapped] private int UsedSpace { get; set; } [NotMapped] public Dictionary ShopSecures { get { if (_shopSecures == null) { // TODO try { _shopSecures = Secures .ToDictionary( shopSecure => shopSecure.SecureId, shopSecure => (shopSecure.Secure as ISecureModel, shopSecure.Count) ); } catch (Exception) { _shopSecures = new(); throw; } UsedSpace = _shopSecures.Select(x => x.Value.Item2).Sum(); } return _shopSecures; } } public static Shop Create(SecuritySystemDatabase context, ShopBindingModel model) { return new Shop() { Id = model.Id, Name = model.Name, Address = model.Address, OpeningDate = model.OpeningDate, MaxSecuresCount = model.MaxSecuresCount, Secures = model.ShopSecures.Select(x => new ShopSecure { Secure = context.Secures.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(ShopBindingModel model) { Name = model.Name; Address = model.Address; OpeningDate = model.OpeningDate; MaxSecuresCount = model.MaxSecuresCount; } public ShopViewModel GetViewModel => new() { Id = Id, Name = Name, Address = Address, OpeningDate = OpeningDate, MaxSecuresCount = MaxSecuresCount, ShopSecures = ShopSecures, UsedSpace = UsedSpace }; public void UpdateSecures(SecuritySystemDatabase context, ShopBindingModel model) { // TODO //context.ShopSecures.RemoveRange(context.ShopSecures.ToList()); //context.SaveChanges(); var shopSecures = context.ShopSecures.Where(shopSecure => shopSecure.SecureId == model.Id).ToList(); if (shopSecures != null && shopSecures.Count > 0) { // удалили те, которых нет в модели context.ShopSecures.RemoveRange(shopSecures.Where(shopSecure => !model.ShopSecures.ContainsKey(shopSecure.SecureId) || shopSecure.Count == 0)); context.SaveChanges(); shopSecures = context.ShopSecures.Where(rec => rec.ShopId == model.Id).ToList(); // обновили количество у существующих записей foreach (var updateSecure in shopSecures) { updateSecure.Count = model.ShopSecures[updateSecure.SecureId].Item2; model.ShopSecures.Remove(updateSecure.SecureId); } context.SaveChanges(); } var shop = context.Shops.First(x => x.Id == Id); foreach (var obj in model.ShopSecures) { context.ShopSecures.Add(new ShopSecure { Shop = shop, Secure = context.Secures.First(x => x.Id == obj.Key), Count = obj.Value.Item2 }); context.SaveChanges(); } _shopSecures = null; } } }