using PlumbingRepairContracts.BindingModels; using PlumbingRepairContracts.ViewModels; using PlumbingRepairDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PlumbingRepairDataBaseImplement.Models { public class Store : IStoreModel { [Required] public string StoreName { get; private set; } = string.Empty; [Required] public string StoreAdress { get; private set; } = string.Empty; [Required] public DateTime OpeningDate { get; private set; } [Required] public int WorkMaxCount { get; private set; } public int Id { get; private set; } private Dictionary _storeWorks = null; [NotMapped] public Dictionary StoreWorks { get { if (_storeWorks == null) { _storeWorks = Works .ToDictionary(recPC => recPC.WorkId, recPC => (recPC.Work as IWorkModel, recPC.Count)); } return _storeWorks; } } [ForeignKey("StoreId")] public virtual List Works { get; set; } = new(); public static Store Create(PlumbingRepairDataBase context, StoreBindingModel model) { return new Store() { Id = model.Id, StoreName = model.StoreName, StoreAdress = model.StoreAdress, OpeningDate = model.OpeningDate, WorkMaxCount = model.WorkMaxCount, Works = model.StoreWorks.Select(x => new StoreWork { Work = context.Works.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(StoreBindingModel model) { StoreName = model.StoreName; StoreAdress = model.StoreAdress; OpeningDate = model.OpeningDate; WorkMaxCount = model.WorkMaxCount; } public StoreViewModel GetViewModel => new() { Id = Id, StoreName = StoreName, StoreAdress = StoreAdress, OpeningDate = OpeningDate, WorkMaxCount = WorkMaxCount, StoreWorks = StoreWorks }; public void UpdateWorks(PlumbingRepairDataBase context, StoreBindingModel model) { var storeWorks = context.StoreWorks.Where(rec => rec.StoreId == model.Id).ToList(); if (storeWorks != null && storeWorks.Count > 0) { // удалили те, которых нет в модели context.StoreWorks.RemoveRange(storeWorks.Where(rec => !model.StoreWorks.ContainsKey(rec.WorkId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateWork in storeWorks) { updateWork.Count = model.StoreWorks[updateWork.WorkId].Item2; model.StoreWorks.Remove(updateWork.WorkId); } context.SaveChanges(); } var store = context.Stores.First(x => x.Id == Id); foreach (var sw in model.StoreWorks) { context.StoreWorks.Add(new StoreWork { Store = store, Work = context.Works.First(x => x.Id == sw.Key), Count = sw.Value.Item2 }); context.SaveChanges(); } _storeWorks = null; } } }