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!

19 comments:

淑娟淑娟 said...

一個人的價值,應該看他貢獻了什麼,而不是他取得了什麼............................................................

鄭湘定 said...

人生是故事的創造與遺忘。............................................................

怡君 said...

支持你就對了!..................................................................

芸茂芸茂 said...

寫文章需要心情~~期待你再一次的好文章............................................................

郁如郁如 said...

A stitch in time saves nine...................................................................

香昱信張君林 said...

每日都有新日光,每日都有新希望。..................................................

琬安琬安 said...

生命的意義,是在於活的充實;而不是在於活得長久。............................................................

可欣可欣 said...

看到你的好文章真是開心 加油囉~..................................................................

童祖如童祖如 said...

祝福您春風得意。............................................................

文王廷 said...

期待新的內容 感謝你............................................................

靖婉亞心 said...

人生像一杯茶,若一飲而盡,會提早見到杯底..................................................

雅明修任 said...

一個人的際遇在第一次總是最深刻的,有時候甚至會讓人的心變成永遠的絕緣。............................................................

老陆 said...

謝謝你的分享,真的太用心了≧﹏≦............................................................

文王廷 said...

感覺很好的blog,祝你開心喔............................................................

淑君韓淑君韓淑君韓 said...

路過~很有趣吶...............................................................

翊翊翊翊張瑜翊翊翊 said...

你怎麼能經過一片海,而忘記它的藍?......................................................................

佳張張張張燕張張張張張 said...

人生匆匆-把握當下,支持鼓勵~事事如意~..................................................

彬彬哲宇 said...

加油-不論如何都期待您的新發表!

張王雅竹欣虹 said...

超棒的,給予最大支持。(* ̄△ ̄*)............................................................