using FlowerShopContracts.BindingModels; using FlowerShopContracts.ViewModels; using FlowerShopDataModels.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 FlowerShopDatabaseImplement.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 DateOpen { get; private set; } [Required] public int MaxCapacity { get; private set; } private Dictionary? _shopFlowers = null; [NotMapped] public Dictionary ShopFlowers { get { if (_shopFlowers == null) { _shopFlowers = Flowers .ToDictionary(x => x.FlowerId, x => (x.Flower as IFlowerModel, x.Count)); } return _shopFlowers; } } [ForeignKey("ShopId")] public virtual List Flowers { get; set; } = new(); public static Shop? Create(FlowerShopDataBase 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, Flowers = model.ShopFlowers.Select(x => new ShopFlower { Flower = context.Flowers.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, ShopFlowers = ShopFlowers, MaxCapacity = MaxCapacity }; public void UpdateFlowers(FlowerShopDataBase context, ShopBindingModel model) { var shopFlowers = context.ShopFlowers.Where(rec => rec.ShopId == model.Id).ToList(); if (shopFlowers != null && shopFlowers.Count > 0) { context.ShopFlowers.RemoveRange(shopFlowers.Where(rec => !model.ShopFlowers.ContainsKey(rec.ShopId))); context.SaveChanges(); foreach (var updateFlower in shopFlowers) { updateFlower.Count = model.ShopFlowers[updateFlower.FlowerId].Item2; model.ShopFlowers.Remove(updateFlower.FlowerId); } context.SaveChanges(); } var shop = context.Shops.First(x => x.Id == Id); foreach (var pc in model.ShopFlowers) { context.ShopFlowers.Add(new ShopFlower { Shop = shop, Flower = context.Flowers.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _shopFlowers = null; } } }