Linq to SQL外键&集合

时间:2010-12-23 16:50:09

标签: 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 个答案:

答案 0 :(得分:2)

这实际上是datacontext的错误,我想你有多个datacontext实例。 好吧,你不能在datacontext中添加任何实体已经通过另一个datacontext实例获取了... 即使你可以通过将datacontext.objecttrackingenabled设置为false然后你可以将它添加到另一个数据上下文然后它肯定会工作....

相关问题