// To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://aka.ms/RazorPagesCRUD. public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } _context.Attach(Product).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(Product.Id)) { return(NotFound()); } else { throw; } } return(RedirectToPage("./Index")); }
public void Update(Product entity) { List <int> newCategories = entity.Categories.Select(x => x.CategoryId).ToList(); if (_entities.Any(p => p.Code == entity.Code && p.Id != entity.Id)) { throw new InvalidOperationException("Product with the same code already exists."); } foreach (var prodToCat in entity.Categories) { prodToCat.ProductId = entity.Id; } if (_context.Entry(entity).State == EntityState.Detached) { _context.Attach(entity); } _context.Entry(entity).State = EntityState.Modified; var existingCategories = _context.ProductsToCategories.Where(c => c.ProductId == entity.Id); foreach (var protToCat in entity.Categories) { //check for new assigned categories if (!existingCategories.Any(e => e.CategoryId == protToCat.CategoryId)) { _context.Entry(protToCat).State = EntityState.Added; } } foreach (var protToCat in existingCategories) { //check for deleted categories connection if (!newCategories.Any(e => e == protToCat.CategoryId)) { _context.Entry(protToCat).State = EntityState.Deleted; } } }