LINQ To SQL: Exception when removing child object from Master-Detail relationship

This week I ran into a quite unexpected exception that was thrown when I tried to remove an object from my LINQ ToSQL DataContext:

System.InvalidOperationException: An attempt was made to remove a relationship between a Master and a Detail. However, one of the relationship’s foreign keys (Detail.MasterId) cannot be set to null..

The example in which this occurred isn’t very exotic, just a Master table and a Detail table and a relationship with a foreign key MasterId in the Detail table (which doesn’t allow null’s). So it should be perfectly valid to remove a row from the Detail table and submit the changes.

Unfortunately there is a problem with this in LINQ To SQL, which is best explained by this post of Beth Massi. She states that to work around this problem you have to manually alter the dbml using an XML editor and add DeleteOnNull=”true” to the association. And yes, this solves the problem.

Beth discovered this problem in VS2008 Beta 2 and it still exists in the final release. Let’s hope the problem is solved with the upcoming SP1…