实体框架4.1 - 外键索引?

时间:2011-04-04 03:23:30

标签: entity-framework entity-framework-4.1

我首先使用的是EF 4代码,我在这里度过了一段时间。我一直收到错误:

{"Introducing FOREIGN KEY constraint 'SalesRepresentative_SalesOrders' on table 'SalesOrders' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors."}

请考虑以下代码。如果我注释掉外键ID字段,它会生成自己的字段并且它可以正常工作,但如果我没有,那么我就会收到错误。

Public Class SalesOrder
        Inherits EntityBase(Of SalesOrder)

#Region "Members/Properties"

        Public Property ID As Integer
        'Public Property CustomerID As Integer
        'Public Property CustomerLocationID As Integer
        'Public Property SalesRepresentativeID As Integer
        'Public Property SalesOrderStatusID As Integer

        Public Overridable Property Customer As Customer
        Public Overridable Property CustomerLocation As CustomerLocation
        Public Overridable Property Items As ICollection(Of SalesOrderItem)
        Public Overridable Property Status As SalesOrderStatus
        Public Overridable Property SalesRepresentative As SalesRepresentative

#End Region

    End Class

Public Class SalesRepresentative
        Inherits EntityBase(Of SalesRepresentative)

#Region "Members/Properties"

        Public Property ID As Integer

        Public Property FirstName As String
        Public Property LastName As String

        Public Overridable Property Customers As ICollection(Of Customer)
        Public Overridable Property SalesOrders As ICollection(Of SalesOrder)

#End Region

    End Class

所以我想知道一些事情:

我是否必须创建外键     财产和导航     属性?我只是创建了     孩子的导航属性     宾语?我只是创建了     父级的导航属性     对象

有人有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您不必在双方都创建导航属性,但必须创建它at least on one side才能在数据库中创建关系。

此外,您不必使用外键属性。此属性在independent and foreign key association之间有所不同。只是说使用外键属性是违反ORM的想法,但它更容易使用EF。

评论FK的部分很有意思。您能否在数据库中验证是否已创建关系以及如何配置它们(级联删除)?

相关问题