using CanteenContracts.BindingModels; using CanteenContracts.View; using CanteenDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CanteenDatabaseImplement.Models { public class Dish : IDishModel { public int Id { get; set; } [Required] public string DishName { get; set; } = string.Empty; [Required] public double Price { get; set; } [Required] public int ManagerId { get; set; } private Dictionary? _dishProducts = null; [NotMapped] public Dictionary DishProducts { get { if (_dishProducts == null) { _dishProducts = Products .ToDictionary(recDP => recDP.ProductId, recDP => (recDP.Product as IProductModel, recDP.CountProducts)); } return _dishProducts; } } [ForeignKey("DishId")] public virtual List Products { get; set; } = new(); public virtual Manager Manager { get; set; } public static Dish Create(CanteenDatabase context, DishBindingModel model) { return new Dish { Id = model.Id, DishName = model.DishName, Price = model.Price, ManagerId = model.ManagerId, Products = model.DishProducts.Select(x => new DishProduct { Product = context.Products.First(y => y.Id == x.Key), CountProducts = x.Value.Item2 }).ToList() }; } public void Update(DishBindingModel model) { DishName = model.DishName; Price = model.Price; } public DishViewModel GetViewModel => new() { Id = Id, DishName = DishName, Price = Price, ManagerId = ManagerId, DishProducts = DishProducts }; public void UpdateDishProduct(CanteenDatabase context, DishBindingModel model) { var dishProduct = context.DishProduct.Where(rec => rec.DishId == model.Id).ToList(); if (dishProduct != null && dishProduct.Count > 0) { context.DishProduct.RemoveRange(dishProduct.Where(rec => !model.DishProducts.ContainsKey(rec.ProductId))); foreach (var updateProduct in dishProduct) { updateProduct.CountProducts = model.DishProducts[updateProduct.ProductId].Item2; model.DishProducts.Remove(updateProduct.ProductId); } context.SaveChanges(); } var dish = context.Dishes.First(x => x.Id == model.Id); foreach (var dp in model.DishProducts.ToList()) { var product = context.Products.First(x => x.Id == dp.Key); context.DishProduct.Add(new DishProduct { Dish = dish, Product = product, CountProducts = dp.Value.Item2 }); model.DishProducts.Remove(dp.Key); } context.SaveChanges(); _dishProducts = null; } } }