Linq to sql Linq到SQL外键&;收藏
我仍然在努力解决LINQ到SQL和外键的关系 我有一张名为“家长”的桌子和另一张名为“孩子”的桌子。我有一个单亲关系,父母可以有多个孩子。我的DBML看起来像:Linq to sql Linq到SQL外键&;收藏,linq-to-sql,Linq To Sql,我仍然在努力解决LINQ到SQL和外键的关系 我有一张名为“家长”的桌子和另一张名为“孩子”的桌子。我有一个单亲关系,父母可以有多个孩子。我的DBML看起来像: <Table Name="" Member="Parents"> <Type Name="Parent"> <Column Member="ParentID" Type="System.String" IsPrimaryKey="true" CanBeNull="false" /> <C
<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();
在我的代码中,我希望执行以下操作:
<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();
//父项已从datacontext加载
父.子=
db.SubmitChanges();
但当我这样做时,我会得到以下错误:
无法更改定义对象标识的成员。
考虑添加具有新标识的新对象,并删除现有的对象。
有人能告诉我如何正确地完成这一点吗?这实际上是datacontext的错误,我认为你有多个datacontext实例。。 你不能在datacontext中添加任何实体,因为它已经通过datacontext的另一个实例获取了。。。
即使您可以将datacontext.ObjectTrackinEnabled设置为false,然后您可以将其添加到另一个数据上下文中,这样也可以确保它能正常工作。…子记录是使用相同的数据上下文检索的还是使用不同的数据上下文检索的?它们是从相同的datacontext检索的。如果您想添加新实体,请确保该实体是新的或是新的没有任何与之相关的datacontext