Wednesday 30 June 2010

LINQ To SQL ERROR: An attempt was made to remove a relationship between a [Table1] and a [Table2].


Full Error
An attempt was made to remove a relationship between a [Table1] and a [Table2]. However, one of the relationship's foreign keys ([Table1].[Foreign Key]) cannot be set to null.


This error usually occurs when trying to called SubmitChanges() on the data context.
For example, I have received this error when trying to commit an object and I have not property build up its properties (one of which may be another table) and when trying to commit this parent object, its related table will be null; this throws an error.

So what you could do is...

1. Ensure the property is present (that is, if you want to commit it in one transaction).
2. Tell the framework to delete child items on submitting... Open the DBML file in Xml Editor (Right Click > Open With...) and find the association and tag "
DeleteOnNull="true" " to the end.
- Alternately, you can specify this in the code...
DataContextInstance.TableName.DeleteAllOnSubmit(items);
3. Remove the table reference as a property all together. Open the DBML file, click on the association and view the properties. Set 'Child Property' to 'False'.

Hope this helps!

No comments: