using SushiBarContracts.BindingModels; using SushiBarContracts.ViewModels; using SushiBarDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using System.Xml.Linq; namespace SushiBarDatabaseImplement.Models { public class Shop : IShopModel { public int Id { get; private set; } [Required] public string ShopName { get; private set; } = string.Empty; [Required] public string Address { get; private set; } = string.Empty; [Required] public DateTime DateOpening { get; private set; } [Required] public int MaxCountSushi { get; private set; } private Dictionary? _shopSushi = null; [NotMapped] public Dictionary ListSushi { get { if (_shopSushi == null) { _shopSushi = ListSushiFk .ToDictionary(recPC => recPC.SushiId, recPC => (recPC.Sushi as ISushiModel, recPC.Count)); } return _shopSushi; } } [ForeignKey("ShopId")] public virtual List ListSushiFk { get; set; } = new(); public static Shop Create(SushiBarDatabase context, ShopBindingModel model) { return new Shop() { Id = model.Id, ShopName = model.ShopName, Address = model.Address, DateOpening = model.DateOpening, MaxCountSushi = model.MaxCountSushi, ListSushiFk = model.ListSushi.Select(x => new ShopSushi { Sushi = context.ListSushi.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; MaxCountSushi = model.MaxCountSushi; } public ShopViewModel GetViewModel => new() { Id = Id, ShopName = ShopName, Address = Address, DateOpening = DateOpening, MaxCountSushi = MaxCountSushi, ListSushi = ListSushi }; public void UpdateSushi(SushiBarDatabase context, ShopBindingModel model) { var shopSushi = context.ShopSushi.Where(rec => rec.SushiId == model.Id).ToList(); if (shopSushi != null && shopSushi.Count > 0) { // удалили те, которых нет в модели context.ShopSushi.RemoveRange(shopSushi.Where(rec => !model.ListSushi.ContainsKey(rec.SushiId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateSushi in shopSushi) { updateSushi.Count = model.ListSushi[updateSushi.SushiId].Item2; model.ListSushi.Remove(updateSushi.SushiId); } context.SaveChanges(); } var shop = context.Shops.First(x => x.Id == Id); foreach (var ss in model.ListSushi) { context.ShopSushi.Add(new ShopSushi { Shop = shop, Sushi = context.ListSushi.First(x => x.Id == ss.Key), Count = ss.Value.Item2 }); context.SaveChanges(); } _shopSushi = null; } } }