Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Without Alter Command, Delete Cascade Rows

Tags:

c#

sql

asp.net

I have to delete a product and its images. Images are in seperate table and productId is acting as foreign key. Here is the single queries to do so.

string deleteImages = @"DELETE FROM [ProductsImages] WHERE ProductId IN (SELECT ProductId FROM [Products] WHERE ProductId = @ProductId)";
string deleteProduct = @"DELETE FROM [Products] WHERE ProductId = @ProductId";
       db.ExecuteNonQuery(deleteImages);
       db.ExecuteNonQuery(deleteProduct);  

I am not getting the way to avoid writing 2 different queries, Is there any help to delete cascade without alter command?

like image 459
Sohail Avatar asked Jan 18 '26 00:01

Sohail


2 Answers

This is something you can define in the database. Just define the foreign key relationship between Products and ProductsImages as "ON DELETE CASCADE". Deleting the product will then automatically delete all associated ProductImages.

like image 165
Twinkles Avatar answered Jan 19 '26 14:01

Twinkles


If you don't want to change the index, you can avoid two round trips by performing multiple operations in one command:

string deleteStuff = @"
  DELETE FROM [ProductsImages] WHERE ProductId = @ProductId;
  DELETE FROM [Products] WHERE ProductId = @ProductId;"
db.ExecuteNonQuery(deleteStuff);
like image 40
Marc Gravell Avatar answered Jan 19 '26 16:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!