using IceCreamShopContracts.BindingModels; using IceCreamShopContracts.ViewModels; using IceCreamShopDataModels.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 IceCreamShopDatabaseImplement.Models { public class Shop : IShopModel { public int Id { get; private set; } [Required] public string ShopName { get; private set; } [Required] public string Address { get; private set; } [Required] public DateTime DateOpen { get; private set; } [Required] public int MaxCapacity { get; private set; } private Dictionary? _shopIceCreams = null; [NotMapped] public Dictionary ShopIceCreams { get { if (_shopIceCreams == null) { _shopIceCreams = IceCreams .ToDictionary(x => x.IceCreamId, x => (x.IceCream as IIceCreamModel, x.Count)); } return _shopIceCreams; } } [ForeignKey("ShopId")] public virtual List IceCreams { get; set; } = new(); public static Shop? Create(IceCreamShopDataBase context, ShopBindingModel model) { if (model == null) return null; return new Shop() { Id = model.Id, ShopName = model.ShopName, Address = model.Address, DateOpen = model.DateOpen, MaxCapacity = model.MaxCapacity, IceCreams = model.ShopIceCreams.Select(x => new ShopIceCream { IceCream = context.IceCreams.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(ShopBindingModel? model) { if (model == null) { return; } ShopName = model.ShopName; Address = model.Address; DateOpen = model.DateOpen; MaxCapacity = model.MaxCapacity; } public ShopViewModel GetViewModel => new() { Id = Id, ShopName = ShopName, Address = Address, DateOpen = DateOpen, ShopIceCreams = ShopIceCreams, MaxCapacity = MaxCapacity }; public void UpdateIceCreams(IceCreamShopDataBase context, ShopBindingModel model) { var shopIceCreams = context.ShopIceCreams.Where(rec => rec.ShopId == model.Id).ToList(); if (shopIceCreams != null && shopIceCreams.Count > 0) { context.ShopIceCreams.RemoveRange(shopIceCreams.Where(rec => !model.ShopIceCreams.ContainsKey(rec.IceCreamId))); context.SaveChanges(); foreach (var updateIceCream in shopIceCreams) { updateIceCream.Count = model.ShopIceCreams[updateIceCream.IceCreamId].Item2; model.ShopIceCreams.Remove(updateIceCream.IceCreamId); } context.SaveChanges(); } var shop = context.Shops.First(x => x.Id == Id); foreach (var pc in model.ShopIceCreams) { context.ShopIceCreams.Add(new ShopIceCream { Shop = shop, IceCream = context.IceCreams.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _shopIceCreams = null; } } }