I have a table A that is referenced by a foreign key constraint from table B. Is there a way to delete a row from table A?
Asked
Active
Viewed 913 times
0
-
What are you using for data access? Entity Framework? – Escobar5 May 12 '17 at 22:09
-
ASP.NET MVC has nothing to do with databases. Are you using Entity Framework? If so, what version? DB-First or Code-First? – Dai May 12 '17 at 22:09
-
@Escobar5 yea EF – john May 12 '17 at 22:10
-
@Dai yes entity framework, version 6 db first – john May 12 '17 at 22:11
-
You need to configure cascade delete for the table, check this: http://stackoverflow.com/a/23667430/641345 – Escobar5 May 12 '17 at 22:13
-
most likely you mucked up your classes in code first then and disabled the cascade delete. Can you show your class with the foreign key? – Travis Acton May 12 '17 at 22:13
-
@Travis Well I have a class product and a class sales... sales(ProductID) points to Products(ID) – john May 12 '17 at 22:16
-
Show your sales class so we can see the decoration you have for it. BUT you probably REALLY do not want to do cascading deletes with those table names. – Travis Acton May 12 '17 at 22:18
-
@Escobar5 what do I have to change "JohnsChildTable" with? The table that points to the other table or..? – john May 12 '17 at 22:18
-
@TravisActon I'm using the auto generated from emdx, nothing special – john May 12 '17 at 22:19
-
Apologies, I swore I read you were using code first and not DB. So before you go ANY further. Would you really want a cascade delete with those table names. If you delete a product then it would delete a sale record. Probably would be best to put an active flag on your product table and just flip the product to inactive if you ever wanted to disable it for customers. This would leave all your records intact. Sorry as I know this is not the answer to your question. – Travis Acton May 12 '17 at 22:22
-
@TravisActon let's say that i want to delete it... what should I do – john May 12 '17 at 22:24
-
Then your modification should really be on the SQL end of things so that everything that touches the table would follow the same business rules even if it were outside your application: Reference this answer for the sql transaction: http://stackoverflow.com/questions/6260688/how-do-i-use-cascade-delete-with-sql-server – Travis Acton May 12 '17 at 22:26
-
@TravisActon can't i do it with c# code? – john May 12 '17 at 22:29
-
I'm not of aware of any automated way to do it in EF other than deleting the children pre parent deletion in code itself. Would be interesting if anyone else has had success using conditional mapping or something. – Travis Acton May 12 '17 at 22:44
1 Answers
1
A way would be to enable cascade delete. Go to SQL Server Management Studio and where you defined the FK set the delete rule to cascade. It is the easiest way but not always the best.

Tom el Safadi
- 6,164
- 5
- 49
- 102