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; private set; } [Required] public string DishName { get; private set; } = string.Empty; [Required] public double Cost { get; private set; } [Required] public int ManagerId { get; private set; } private Dictionary? _dishProducts = null; public Dictionary DishProduct { get { if (_dishProducts == null) { _dishProducts = Products .ToDictionary(recPC => recPC.ProductId, recPC => (recPC.Product as IProductModel, recPC.CountProduct)); } return _dishProducts; } } [ForeignKey("DishId")] public virtual List Products { get; set; } = new(); public static Dish? Create(CanteenDatabase context, DishBindingModel model) { return new Dish() { Id = model.Id, DishName = model.DishName, Cost = model.Cost, Products = model.DishProducts.Select(x => new DishProduct { Product = context.Products.First(y => y.Id == x.Key) }).ToList() }; } public void Update(DishBindingModel model) { DishName = model.DishName; Cost = model.Cost; } public DishViewModel GetViewModel => new() { Id = Id, DishName = DishName, Cost = Cost, DishProducts = DishProduct, ManagerId = ManagerId }; public Dictionary DishProducts => throw new NotImplementedException(); public void UpdateProduct(CanteenDatabase context, DishBindingModel model) { var dishProducts = context.DishProducts.Where(record => record.ProductId == model.Id).ToList(); if (dishProducts != null && dishProducts.Count > 0) { context.DishProducts.RemoveRange(dishProducts.Where(record => !model.DishProducts.ContainsKey(record.ProductId))); context.SaveChanges(); } var product = context.Products.First(x => x.Id == Id); foreach (var pc in model.DishProducts) { context.DishProducts.Add(new DishProduct { Product = product, Dish = context.Dishes.First(x => x.Id == pc.Key), }); context.SaveChanges(); } _dishProducts = null; } } }