Home > Back-end >  How to delete its products too, while deleting a category?
How to delete its products too, while deleting a category?

Time:12-20

I want to delete category's products (Products connected to Catgory column with CategoryId and each product has only 1 category) while deleting category itself. In my opinion, I should delete products where their CategoryId is equal to id of category that I want to delete. And then delete category itself. But could not write code for deleting products:

`

_context.Products.Remove(category.Products); // That line is not true
_context.ProductCategories.Remove(category);
_context.SaveChanges();

`

Note: Code is written in .NET MVC

Tried to delete category, but product should have category. If category is deleted without products, then there will be error, because category is required for products. That's why I need to delete specific products firstly, then category.

CodePudding user response:

you can use the Where method to filter the products based on the category id, and then use the RemoveRange method to delete all the matching products in one go.

// Get the category that you want to delete, along with its associated products
var category = _context.ProductCategories
    .Include(c => c.Products)
    .SingleOrDefault(c => c.Id == id);

// Delete the products
_context.Products.RemoveRange(category.Products);

// Delete the category
_context.ProductCategories.Remove(category);

// Save the changes to the database
_context.SaveChanges();

Another approach is to use the Include method to eagerly load the products when you retrieve the category, and then use the RemoveRange method to delete all the products at once.

var category = _context.ProductCategories
    .Include(c => c.Products)
    .SingleOrDefault(c => c.Id == id);


_context.Products.RemoveRange(category.Products);    

_context.ProductCategories.Remove(category);    

_context.SaveChanges();
  • Related