public async Task UpdateAsync(T entity) { _dbContext.Entry(entity).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { await PopulateLists(); return(Page()); } if (!CatalogCategoryModel.Any(x => x.Selected)) { await PopulateLists(); ModelState.AddModelError("", "Selecciona pelo menos uma categoria"); return(Page()); } //Sku CatalogItem.Sku = $"{_context.CatalogTypes.Find(CatalogItem.CatalogTypeId).Code}-{CatalogItem.Id}"; //Save Image if (Picture?.Length > 0) { if (!string.IsNullOrEmpty(CatalogItem.PictureUri)) { _service.DeleteFile(_backofficeSettings.GroceryProductsPictureFullPath, Utils.GetFileName(CatalogItem.PictureUri)); } CatalogItem.PictureUri = _service.SaveFile(Picture, _backofficeSettings.GroceryProductsPictureFullPath, _backofficeSettings.GroceryProductsPictureUri, CatalogItem.Id.ToString(), true, 500, 500).PictureUri; } //CatalogCategories var catalogCategoriesDb = await _context.CatalogCategories .Include(x => x.Category) .Where(x => x.CatalogItemId == CatalogItem.Id) .ToListAsync(); //Novos foreach (var item in CatalogCategoryModel.Where(x => x.Selected).ToList()) { if (catalogCategoriesDb == null || !catalogCategoriesDb.Any(x => x.CategoryId == item.CategoryId)) { CatalogItem.CatalogCategories.Add(new CatalogCategory { CategoryId = item.CategoryId }); } foreach (var child in item.Childs.Where(x => x.Selected).ToList()) { if (catalogCategoriesDb == null || !catalogCategoriesDb.Any(x => x.CategoryId == child.CategoryId)) { CatalogItem.CatalogCategories.Add(new CatalogCategory { CategoryId = child.CategoryId }); } } } //Remover foreach (var item in CatalogCategoryModel.ToList()) { if (!item.Selected) { var catalogCategory = catalogCategoriesDb.SingleOrDefault(x => x.CategoryId == item.CategoryId); if (catalogCategory != null) { _context.Entry(catalogCategory).State = EntityState.Deleted; } } foreach (var child in item.Childs.Where(x => !x.Selected).ToList()) { var catalogCategory = catalogCategoriesDb.SingleOrDefault(x => x.CategoryId == child.CategoryId); if (catalogCategory != null) { _context.Entry(catalogCategory).State = EntityState.Deleted; } } } _context.Attach(CatalogItem).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CatalogItemExists(CatalogItem.Id)) { return(NotFound()); } else { throw; } } return(RedirectToPage("./Index")); }