I have a simple model to keep track of locker rentals as a way to learn EF Code First and DDD principles. The model has these requirements:
The model is setup like this:
Organization holds two collections; one to hold a collection of lockers and one to hold a collection of rental periods. Locker and rental period do not hold references to their parent organization to keep with DDD tradition, however they both contain a required foreign key to their parent organization. The locker and rental period both contain a collection of rentals. The rental has a required foreign key to a locker and a required foreign key to a rental period. The image below will give a good idea of what my model looks like.
It would make since that organization is modeled with cascade delete so that when the organization is deleted it deletes all associated lockers and rental periods. But I believe it would also make sense for locker and rental period to be modeled with cascade delete so that if a locker gets deleted than all associated rentals also get deleted. The same thing applies to a rental period. When I configure it like that EF tells me that I cannot do that since it could create cycles or multiple cascade paths. However, if I take any one relationship (doesn't matter which one) and turn off cascade delete, than it will create the database just fine. I imagine that fixes the multiple cascade path problem.
Because cascade on delete doesn't work in this model, that seems to give an indication to me that my problem might be modeled wrong. I've thought about this for quite a while and I can't come up with any way to model this problem that will work with cascade delete.
I've included the test project below (Visual Studio 2010 solution). The only thing that needs to be changed is the connection string in App.config. I'm open to all suggestions as I am just beginning to learn EF Code First and DDD principles.
It is actually not modeled in wrong way but simply SQL Server (not EF) doesn't allow multiple cascade paths. If your Organization
is deleted it triggers cascade delete of both Lockers
and RentalPeriods
an they both trigger cascade delete to Rentals
= issue. You should be fine if only one of them triggers cascade delete to Rentals
. You must only ensure that Lockers
or RentalPeriods
are not deleted separately. If they are you must correctly handle deletion of Rentals
manually or you must use database triggers (the common way to avoid this issue).