实体框架是否支持循环引用?

Vag*_*lov 13 entity-framework

我有父/子关系中的两个实体.另外,parent包含对"main"子项的引用,因此简化模型如下所示:

class Parent
{
   int ParentId;
   int? MainChildId;
}

class Child
{
   int ChildId;
   int ParentId;
}
Run Code Online (Sandbox Code Playgroud)

我现在遇到的问题是EF似乎无法在单个操作中处理父和子的创建.我收到错误"System.Data.UpdateException:无法确定依赖操作的有效排序.由于外键约束,模型要求或存储生成的值,可能存在依赖关系."

MainChildId是可空的,因此应该可以生成父项,子项,然后使用新生成的ChildId更新父项.这是EF不支持的东西吗?

Cra*_*ntz 5

不,它得到了支持.使用GUID键或可指定序列进行尝试.错误意味着它的确如此:EF无法一步到位地弄清楚如何做到这一点.你可以分两步完成(两次调用SaveChanges()).

  • 如果需要两个步骤,那么我会说它不受支持,因为在原始描述中我提到我想在单个操作中处理它,即没有多次调用SaveChanges.我收到了微软的答复,他们说这不是由当前版本的EF处理的:http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/d8691dc2-bb13-4e5d-959b-2ae40a9caec5 (3认同)

Jam*_*ose 5

我有这个问题.明显的"循环引用"就是很好的数据库设计.像"IsMainChild"这样的子表上有一个标志是糟糕的设计,属性"MainChild"是父项的属性而不是子项,因此父项中的FK是合适的.

EF4.1需要找到一种本地处理这种类型关系的方法,而不是强迫我们重新设计我们的数据库以适应框架中的缺陷.

无论如何,我的解决方法是执行几个步骤(就像您在编写存储过程时可能会这样做)唯一的问题是绕过上下文的更改跟踪.

Using context As New <<My DB Context>>

  ' assuming the parent and child are already attached to the context but not added to the database yet

  ' get a reference to the MainChild but remove the FK to the parent
  Dim child As Child = parent.MainChild
  child.ParentID = Nothing

  ' key bit detach the child from the tracking context so we are free to update the parent
  ' we have to drop down to the ObjectContext API for that
  CType(context, IObjectContextAdapter).ObjectContext.Detach(child)

  ' clear the reference on the parent to the child
  parent.MainChildID = Nothing

  ' save the parent
  context.Parents.Add(parent)
  context.SaveChanges()

  ' assign the newly added parent id to the child
  child.ParentID = parent.ParentID

  ' save the new child
  context.Children.Add(child)
  context.SaveChanges()

  ' wire up the Fk on the parent and save again
  parent.MainChildID = child.ChildID
  context.SaveChanges()  

  ' we're done wasn't that easier with EF?

End Using  
Run Code Online (Sandbox Code Playgroud)