I want to be able to check if deleting a row from a table in SQL Server 2008 will fail because of a Foreign Key violation without attempting to delete it.
Basically, I don’t want to show the user a delete button if they are not going to be able delete it because the key is used elsewhere.
I am needing this in many places in the application so don’t really want to have to write the checks manually to see if it safe to delete the row. Any suggestions on the best way to achieve this?
I am using entity framework for access to the data.
There is no quick and easy way to check this. You could probably build something dynamic using
information_schema, but it will undoubtedly be ugly and not very fast.The absolute best choice is the few lines of custom code that it takes to verify per location.
Another option would be to start a transaction, try the delete. If it fails, then you know. If it succeeds, roll back the transaction, and you know the delete is possible. This is still ugly and is using transactions in a somewhat broken way, but it would work. Make sure cascade deletes aren’t on for the table, though.