0
votes

I'm a still trying to wrap myself around LINQ to SQL and foreign key relationships.

I have a table called "Parent" and another called "Children". I have a OneToMany relationship, where a Parent can have multiple Children. My DBML looks something like:

<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>

In my code, I would like do to something like:

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

But when I do that I get the following error:

A member defining the identity of the object cannot be changed. Consider adding a new object with new identity and deleting the existing one instead.

Can anyone tell me how to properly accomplish this?

1
Were the child records retrieved using the same data context or a different one? - Randy Minder
They were retrieved from the same datacontext. - Addy

1 Answers

2
votes

this is actually the error of datacontext,i think u have multiple instance of datacontext.. well u can not add any entity in datacontext witch is already fetched through another instance of datacontext... even u can so it by setting datacontext.objecttrackingenabled to false and then u can add it to another data context then it will work for sure....