2010-12-23 65 views
0

我仍然試圖繞過LINQ to SQL和外鍵關係。Linq to SQL外鍵和集合

我有一張名爲「Parent」的表,另一個名爲「Children」。我有一個OneToMany關係,父母可以有多個孩子。我DBML看起來像:

<Table Name="" Member="Parents"> 
<Type Name="Parent"> 
    <Column Member="ParentID" Type="System.String" IsPrimaryKey="true" CanBeNull="false" /> 
    <Column Member="ChildID" Type="System.String" CanBeNull="false" /> 
    <Association Name="Parent_Child" Member="Childs" ThisKey="ParentID" OtherKey="ParentID" Type="Child" /> 
</Type> 
</Table> 
<Table Name="" Member="Childs"> 
<Type Name="Child"> 
    <Column Member="ChildID" Type="System.String" IsPrimaryKey="true" CanBeNull="false" /> 
    <Column Member="ParentID" Type="System.String" CanBeNull="false" /> 
    <Association Name="Parent_Child" Member="Parent" ThisKey="ParentID" OtherKey="ParentID" Type="Parent" IsForeignKey="true" /> 
</Type> 
</Table> 

在我的代碼,我想這樣做的東西,如:

// parent has already been loaded from the datacontext 
parent.Childs = <some collection of children> 
db.SubmitChanges(); 

但是,當我這樣做,我得到以下錯誤:

成員定義對象的身份不能改變。 考慮添加一個具有新身份的新對象,並刪除現有的對象。

誰能告訴我如何正確完成這個?

+1

是否使用相同的數據上下文或不同的子記錄檢索? – 2010-12-23 17:01:40

+0

它們是從相同的數據上下文中檢索的。 – Addy 2010-12-23 17:08:30

回答

2

這其實是的datacontext的錯誤,我覺得你有DataContext的多實例.. 以及你無法加入的datacontext女巫任何實體通過的datacontext的另一個實例已經取... 甚至U可以因此通過設置datacontext.objecttrackingenabled爲false,然後你可以將其添加到另一個數據上下文,那麼它會肯定工作....