I have a table of users (User), and need to create a new table to track which users have referred other users. So, basically, I'm creating a many-to-many relation between rows in the same table.
So I'm trying to create table UserReferrals with the columns UserId and UserReferredId. I made both columns a compound primary key. And both columns are foreign keys that link to User.UserID.
Since deleting a user should also delete the relationship, I set both foreign keys to cascade deletes. When the user is deleted, any related rows in UserReferrals should also delete.
But this gives me the message:
'User' table saved successfully
'UserReferrals' table Unable to create relationship 'FK_UserReferrals_User'. Introducing FOREIGN KEY constraint 'FK_UserReferrals_User' on table 'UserReferrals' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FORE开发者_运维问答IGN KEY constraints. Could not create constraint. See previous errors.
I don't get this error. A cascading delete only deletes the row with the foreign key, right? So how can it cause "cycling cascade paths"?
Thanks for any tips.
If you have FK's on a table (A) that references a table (B) that in turn also has a relationship to (A), or an FK that references a PK in the same table, it can introduce a scenario where it cycles. Sometimes this isn't logically possible - but in pure theory it's possible in the eyes of the SQL engine.
This isn't avoidable. Typically we handle these in an SP (which in EF we can map to the delete method).
If you were to allow cascading deletes, the deletion of a person whose UserId appears in the UserReferredId field of other users would cause those user to be deleted too! I suspect what you want is to have the value of UserReferredId set to null if the User whom is tied to it is deleted.
There are several approaches ranging from a table trigger on the delete command to using a store procedure for your deletion. Ignoring the triggers are evil argument, one could create something like:
create trigger clearUserReferredIdOnUserDelete on Users after delete as update users set UserReferredId = null where UserReferredId in (select userid from deleted)
That's untested but should be close.
P
After thinking about this, I'm starting to think the problem is not so much related to cyclic cascade paths as much as it may be related to multiple cascade paths.
Although the two UserIDs in my joining table will always be different, nothing prevents them from being the same. If they both referred to the same user, and that user was deleted, there would be multiple cascade paths to the joining table.
精彩评论