I try to keep up with blog posts on the net which involve the entity framework, and this afternoon I came across this post where someone had been experimenting with EF4 and encountered some cases where things didn’t behave as they expected. I started to respond in a comment to that blog but the comment starting getting awfully long. So here’s a more complete response (which I’ll then refer to in a short comment). Please take a moment now to go read the other post for context. OK. Now that you are back, here’s my response:
When you use FK-relationships (the default with EF4), there are 3 main kinds of configurations you can encounter which each have slightly different behaviors. Let me see if I can explain so that you can understand better why the EF behaves the way it does.
Another variation to be aware of here in the first two cases is that you can have cascade delete behavior turned on. If you do, then deleting the principal entity will cause the dependent entity to also be deleted. Cascade delete does NOT, however, affect what happens when you remove the relationship. The only case in current releases of the EF where removing the relationship will cause the dependent entity to be removed is #3 above where the primary key of the dependent includes a foreign-key to the principal. An additional option we’d like to add for a future release of the EF is the ability to opt-in to an auto-delete orphans or cascade relationship or whatever you might want to call it behavior where case #1 above could have an additional option turned on so that it would delete the dependent rather than throwing an exception, but for now this is logic you will have to write yourself.