I have a Logs table in my database where I’m storing records of user actions. There’s a column for UserID, which is foreign-keyed to the Users table to check that the UserID exists when a log is added. However, attempting to delete a user causes a constraint failure because it leaves a UserID in the Logs table that no longer exists in the Users table. Deleting the offending rows from Logs isn’t an option, because the whole point is to have persistent records (so that we can find out who broke what, basically) so deleting all actions by that user rather defeats the purpose.
Is there a simple way to have it check the constraint when inserting new logs (to make sure the user exists at the time) but not when deleting a user? I’m accessing the DB via LINQ, so my queries are in C#, not SQL, so anything that requires that is out, but I have access to the database through MS SQL Server Management Studio, so I can do what I like with it.
EDIT for slight clarification: the value of knowing who made an action is not just in accountability; it’s useful in determining if an issue is user-specific, organisation-specific, or system-wide, which can greatly narrow down the list of possible causes. Once a user is deleted, it’s still worth keeping their actions, and it’s still useful to know which actions were by that user, for various reasons – for example, when tracking down an issue caused by one user doing a certain combination of things (eg. two actions that are fine separately but cause errors when one immediately follows another).
If you really want to keep the logs, you should never fully delete the user.
Rather than deleting the user record, change its state to indicate it is deleted, so your database still has referential integrity.
Alternatively, switch on cascading deletes, so when you delete the user, the logs are all removed at the same time, which is another way of maintaining referential integrity.