Question

It seems an odd question I'm sure to some of you, but being self-taught, I've never had someone else impart best-practice on me.

In short, lets assume I have a database table (table 1) linked to another database table (table 2). A relationship exists between them to specify that should a record in table 1 be deleted, No Action should be taken in table 2 - reinforcing referential integrity and stopping records from table 1 being deleted if there are linked records in table 2.

Therefore if I was to programmatically delete a record in table 1 that had linked records in table 2 (for example using ADO.NET) I would get an error.

The question is, should I reinforce the logic by checking for linked records before even requesting the deletion of a record. As far as I see it, this doubles up on checks (queries) and provides the added security of someone changing the relationship in the database but ensuring the logic is still adhered to - at a small cost in resources for every check, but what is the right way???

Was it helpful?

Solution

Checking before you try to delete may seem like a good idea but IMO it is a little bit redundant (unless you only have 1 user) as it will not guarantee that it is safe to delete, the state of the database could very easily be changed by another user in-between performing the check and issuing the delete command.

I would let the database handle the delete and then catch and handle specific exceptions if they are thrown in the code. I think you would get a SqlException in this case and then you would need to examine the error code for the errors you want to handle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top