Pregunta

Tengo una tabla de usuarios (usuario), y la necesidad de crear una nueva tabla para realizar un seguimiento de lo que los usuarios se han referido otros usuarios. Así que, básicamente, estoy creando una relación de muchos a muchos entre las filas de la misma tabla.

Así que estoy tratando de crear UserReferrals tabla con las columnas ID de usuario y UserReferredId. Hice dos columnas una clave primaria compuesta. Y las dos columnas son las claves externas que enlazan con User.UserID.

Desde la eliminación de un usuario también debe eliminar la relación, que establece dos claves externas a las eliminaciones en cascada. Cuando se elimina el usuario, cualquier filas relacionadas en UserReferrals también deben eliminar.

Pero esto me da el mensaje:

'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 FOREIGN KEY constraints. Could not create constraint. See previous errors.

No me sale este error. Una eliminación en cascada sólo elimina la fila con la clave externa, ¿verdad? Entonces, ¿cómo puede hacer que "el ciclismo rutas en cascada"?

Gracias por cualquier consejo.

¿Fue útil?

Solución 3

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.

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top