A while ago I had a discussion with my colleagues about the persistence of Domain Models and whether we should enforce foreign-key constraints at the database level.
My first reaction was that the very use of a relational database implied the enforcement of such constraints, but some argued that the database should be seen as nothing but a persistence mechanism and therefore we should avoid placing any business logic in it. We ended up by not using foreign-key constraints.
Here is my question (I hope it is not too generic): is it considered good practice to enforce key constraints in theses cases?
Enforce constraints, but do NOT rely on them in your business logic
But if you and your team are able to write bug-free software and handle all possible exception scenarios in your code (including hardware/network/dummy-user/programmer-error failures), then "Hei, why bother with redundant FK constraints...." - -teaser-
If you want to follow the Domain Driven Design paradigm, then the answer would be yes for anything within an Aggregate, and no for any cross-Aggregate links.
In nearly all cases, you want anything under the Aggregate Root to be deleted when the Root itself is deleted, and so having foreign keys that represent this, with cascading deletes, allow you to achieve this at the database level. You could also have your Repositories do the cascading deletes themselves if you didn't want to do it at a DB level, but the point still stands that Aggregate children should not exist without the Root.
For cross-Aggregate concerns, you'll probably be dealing with business decisions as to what should happen when one or the other is removed. Often you'll want to deal with this asynchronously to allow for scalability, and so your domain model ends up being eventually consistent. Therefore, it doesn't make sense in these cases to enforce foreign keys as there'll be a window of time where one or the other key may not exist.
Hope that helps! And for more info, definitely check out Evans' book on Domain Driven Design - and the many links around the web too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With