An attempt was made to remove a relationship between a (*) and a (*). However, one of the relationship's foreign keys (X) cannot be set to null

database, default-value, foreign-keys, linq-to-sql

Solution

I assume that you are trying to "reset" a reference to its default value by assigning `null` to it, expecting L2S to adopt the database default. However, as for L2S, you're only nullifying a foreign key. It's not aware of any defaults in the database.

So you have to change the reference by setting it to the default lookup object yourself. You could do that by adding a `Reset()` method to your classes, so you don't have to scatter this code all over the place.

Problem

I have an SQL Server table structure where in some columns are foreign keys that refer to different look up tables. These columns are created as `NOT NULL` and with `DEFAULT value = 1` as the look up value for `ID = 1` is the default value I want to assign in case `NULL` is passed while saving a record. However, I got below error while trying to `Add/Update/Delete` records of this child table. ``` An attempt was made to remove a relationship between a (*) and a (*). However, one of the relationship's foreign keys (X) cannot be set to null. ``` I tried to search a lot but I got solution to change LINQ to SQL code or XML manually for resolving this. I cannot do that because in future when ever the table gets changed, I'll have to make sure the manual change is applied every time. Also, I can not change my columns to accept `NULL` because that will impact other applications using the same table through LINQ To SQL. I need more manageable solution for this.

Original source