为什么代码优先EF在三个实体相互关联时生成循环引用?

时间:2012-08-23 11:08:53

标签: entity-framework ef-code-first

我在EF Code First 4.3中针对SqlCe4.0客户端创建数据库时遇到循环引用错误。为了清楚起见,我附上了我想要的数据库模式的图片。仅供参考,我已在SQL Server 2008中成功创建了所需的架构。

  

参照关系将导致不允许循环引用。 [约束名称= FK_Routes_Seasons_SeasonID]

  • 路线与季节有一个多关系
  • 合同与路线有一对多的关系
  • 合约与季节有一个多关系

Desired DB Schema

我的代码是:

Public Class Route
    Public Property RouteID as Integer

    Public Property SeasonID as Integer
    Public Overridable Property Season As Season

    Public Overridable Property Contracts As ICollection(Of Contract)
End Class

Public Class Season
    Public Property SeasonID as Integer

    Public Overridable Property Routes As ICollection(Of Routes)
    Public Overridable Property Contracts As ICollection(Of Contract)
End Class

Public Class Contract
    Public Property ContractID As Integer

    Public Property RouteID As Integer
    Public Overridable Property Route As Route

    Public Property SeasonID As Integer
    Public Overridable Property Season As Season
End Class

1 个答案:

答案 0 :(得分:2)

它不一定是循环的,但是你在删除树的同一个表中有多个引用。请参阅this postthis post

在你的表格中:

  

季节 - >路线 - >合同

     

季节 - >合同

您需要对其进行设置,以便其中一个关系不会级联删除。我不熟悉VB,但在C#中你可以这样设置流利:

modelBuilder.Entity<Routes >()
            .HasRequired(r => r.Season )
            .WithMany(s => s.Routes)
            .HasForeignKey(r => r.SeasonID );
            .WillCascadeOnDelete(false);