1

我收到错误:

{“ReferentialConstraint 中的依赖属性映射到商店生成的列。列:'FeeID'。”}

设置:我手动创建了数据库(SQL Server 2012 和 SSMS)

我没有 edmx 文件

我有两个类FeeMetaDataFee,它们映射到数据库中的两个表(PFD.FeeMetaDataPFD.Fees

数据库结构

FeeMetadata
------------ 
FeeID  BIGINT  IDENTITY(1,1) PRIMARY KEY 
Something VARCHAR(25) NOT NULL

Fees
------------ 
FeeID  BIGINT  PRIMARY KEY NOT NULL
FeeBatchID  BIGINT NOT NULL
PersonID BIGINT 
Amount DECIMAL(18,2) NOT NULL
DueDate DATE NOT NULL

FeeMetadata.FeeID 和 Fees.FeeID 之间存在一对一的关系

类结构

Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Namespace PFD
    <Table("FeeMetadata", Schema:="PFD")>
    Public Class FeeMetadata

        Public Sub New()
            MyBase.New()
        End Sub

        Public Sub New(ByVal tFee As SOACourt_v1)
            Me.New()
            Me.PfdFee = New PFD.Fee(tFee)
        End Sub

        <Key>
        <DatabaseGenerated(DatabaseGeneratedOption.Identity)>
        Public Property FeeID As Int64

        Public Property Something As String

        <ForeignKey("FeeID")>
        Public Property PfdFee As PFD.Fee
    End Class
End Namespace





Namespace PFD
<Table("Fees", Schema:="PFD")>
Public Class Fee
    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal tFee As SOACourt_v1)
        Me.New()
        Me.Amount = tFee.Amount
        Me.DueDate = tFee.DueDate
    End Sub


    <DatabaseGenerated(DatabaseGeneratedOption.None)>
    Public Property FeeID As Int64

    Public Property FeeBatchID As Int64 = 0

    Public Property PersonID As Int64? = 0

    Public Property Amount As Decimal

    Public Property DueDate As Date = Date.Today
End Class
End Namespace

用法

Using tContext As FeesContext = New FeesContext
    For Each tFee As SOACourt_v1 In tFees
        tContext.FeeMetadata.Add(New PFD.FeeMetadata(tFee))
    Next
    tContext.SaveChanges()     '  <---- Error occurs here
End Using

关于导致错误的任何想法:

{“ReferentialConstraint 中的依赖属性映射到商店生成的列。列:'FeeID'。”}

4

1 回答 1

5

虽然我还没有使用 EF 代码优先,但如果您在模型图中错误地设置实体关系,这看起来与您遇到的错误相同。特别是,在我看来,您的外键设置是反向的。

该错误是因为您告诉 Entity Framework 将该字段用作andFeeId之间的外键,但该字段是在类中自动生成的。这几乎肯定不是你打算做的。FeeMetaDataFeeFeeMetaData

如果Fee是主表并且FeeMetaData有外键,那么你应该把标识字段放在Fee. 如果表是相反的,那么你的类是倒退的,你应该定义Fee一个FeeMetaData具有FeeId作为外键的属性。

于 2012-12-21T02:02:24.380 回答