private void UpdateProductsSubCategories(string[] selectedSubCategories, Product productToUpdate) { if (selectedSubCategories == null) { productToUpdate.ProductSubcategories = new List <ProductSubcategory>(); return; } var selectedSubCategoriesHS = new HashSet <string>(selectedSubCategories); var productSubCategories = new HashSet <int> (productToUpdate.ProductSubcategories.Select(c => c.SubCategory.Id)); foreach (var subcat in _context.SubCategories) { if (selectedSubCategoriesHS.Contains(subcat.Id.ToString())) { if (!productSubCategories.Contains(subcat.Id)) { productToUpdate.ProductSubcategories.Add(new ProductSubcategory { ProductId = productToUpdate.Id, SubCategoryId = subcat.Id }); } } else { if (productSubCategories.Contains(subcat.Id)) { ProductSubcategory courseToRemove = productToUpdate.ProductSubcategories.SingleOrDefault(i => i.SubCategoryId == subcat.Id); _context.Remove(courseToRemove); } } } }
public void UpdateProductSubcategory(WmIdentityDbContext context, string[] selectedSubcategories, Product productToUpdate) { if (selectedSubcategories == null) { productToUpdate.ProductSubcategories = new List <ProductSubcategory>(); return; } var selectedSubcategoriesHS = new HashSet <string>(selectedSubcategories); var productSubcategories = new HashSet <int> (productToUpdate.ProductSubcategories.Select(c => c.SubCategory.Id)); foreach (var subcategory in context.SubCategories) { if (selectedSubcategoriesHS.Contains(subcategory.Id.ToString())) { if (!productSubcategories.Contains(subcategory.Id)) { productToUpdate.ProductSubcategories.Add( new ProductSubcategory { ProductId = productToUpdate.Id, SubCategoryId = subcategory.Id, }); } } else { if (productSubcategories.Contains(subcategory.Id)) { ProductSubcategory subcategoryToRemove = productToUpdate .ProductSubcategories .SingleOrDefault(i => i.SubCategoryId == subcategory.Id); context.Remove(subcategoryToRemove); } } } }