using FoodOrdersContracts.BindingModels; using FoodOrdersContracts.ViewModels; using FoodOrdersDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace FoodOrdersDatabaseImplement.Models { 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 MaxCountDishs { get; set; } private Dictionary? _shopDishs = null; [NotMapped] public Dictionary ShopDishs { get { if (_shopDishs == null) { _shopDishs = Dishs .ToDictionary(x => x.DishId, x => (x.Dish as IDishModel, x.Count)); } return _shopDishs; } } [ForeignKey("ShopId")] public virtual List Dishs { get; set; } = new(); public static Shop Create(FoodOrdersDatabase context, ShopBindingModel model) { return new Shop() { Id = model.Id, ShopName = model.ShopName, Address = model.Address, DateOpening = model.DateOpening, MaxCountDishs = model.MaxCountDishs, Dishs = model.ShopDishs.Select(x => new ShopDish { Dish = context.Dishs.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; MaxCountDishs = model.MaxCountDishs; } public ShopViewModel GetViewModel => new() { Id = Id, ShopName = ShopName, Address = Address, DateOpening = DateOpening, MaxCountDishs = MaxCountDishs, ShopDishs = ShopDishs }; public void UpdateDishs(FoodOrdersDatabase context, ShopBindingModel model) { var shopDishs = context.ShopDishs.Where(rec => rec.ShopId == model.Id).ToList(); if (shopDishs != null && shopDishs.Count > 0) { context.ShopDishs.RemoveRange(shopDishs.Where(rec => !model.ShopDishs.ContainsKey(rec.DishId))); context.SaveChanges(); foreach (var updateDish in shopDishs) { if (model.ShopDishs.ContainsKey(updateDish.DishId)) { updateDish.Count = model.ShopDishs[updateDish.DishId].Item2; model.ShopDishs.Remove(updateDish.DishId); } } context.SaveChanges(); } var shop = context.Shops.First(x => x.Id == Id); foreach (var ic in model.ShopDishs) { context.ShopDishs.Add(new ShopDish { Shop = shop, Dish = context.Dishs.First(x => x.Id == ic.Key), Count = ic.Value.Item2 }); context.SaveChanges(); } _shopDishs = null; } } }