using SushiBarContracts.BindingModels; using SushiBarContracts.ViewModels; using SushiBarDataModels.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 SushiBarDatabaseImplement.Models { public class Task : ITaskModel { public int Id { get; set; } [Required] public DateTime TaskDate { get; set; } [Required] public SushiBarDataModels.Enum.TaskStatus Status { get; set; } [Required] public double FullPrice { get; set; } public int PlaceId { get; set; } public int CookId { get; set; } public int BuyerId { get; set; } private Dictionary? _taskMenu = null; [NotMapped] public Dictionary TaskMenus { get { if(_taskMenu == null) { _taskMenu = Menus.ToDictionary(recTM => recTM.MenuId, recTM => (recTM.Menu as IMenuModel, recTM.Count)); } return _taskMenu; } } [ForeignKey("TaskId")] public virtual List Menus { get; set; } = new(); public static Task Create(SushiBarDatabase context, TaskBindingModel model) { return new Task() { Id = model.Id, TaskDate = model.TaskDate, Status = model.Status, FullPrice = model.FullPrice, PlaceId = model.PlaceId, CookId = model.CookId, BuyerId = model.BuyerId, Menus = model.TaskMenus.Select(x => new TaskMenu { Menu = context.Menus.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList(), }; } public void Update(TaskBindingModel model) { Status = model.Status; } public TaskViewModel GetViewModel => new() { Id = Id, TaskDate = TaskDate, Status = Status, FullPrice = FullPrice, PlaceId = PlaceId, CookId = CookId, BuyerId = BuyerId, TaskMenus = TaskMenus }; public void UpdateMenus(SushiBarDatabase context, TaskBindingModel model) { var taskMenus = context.TaskMenus.Where(rec => rec.TaskId == model.Id).ToList(); if(taskMenus != null && taskMenus.Count > 0) { context.TaskMenus.RemoveRange(taskMenus.Where(rec => !model.TaskMenus.ContainsKey(rec.MenuId))); context.SaveChanges(); foreach(var updateMenu in taskMenus) { updateMenu.Count = model.TaskMenus[updateMenu.MenuId].Item2; model.TaskMenus.Remove(updateMenu.MenuId); } context.SaveChanges(); } var task = context.Tasks.First(x => x.Id == Id); foreach(var rc in model.TaskMenus) { context.TaskMenus.Add(new TaskMenu { Task = task, Menu = context.Menus.First(x => x.Id == rc.Key), Count = rc.Value.Item2 }); context.SaveChanges(); } _taskMenu = null; } } }