1

我有以下实体:

Partial Public Class Workflow
    Sub New()
        Activities = New List(Of WFActivity)
    End Sub
    <Key()>
    Public Property ID As Long
    Public Property Customer As Customer
    <Required(), MaxLength(100)>
    Public Property Name As String
    Public Property Activities As List(Of WFActivity)
End Class

要添加和更新实体,我使用以下过程:

Public Sub SaveWorkflow(ByVal WF As Workflow)
    Dim wfa As WFActivity
    Try
        Using ctx = New MyContext

            ctx.Workflow.Add(WF)
            If WF.ID > 0 Then
                ctx.Entry(WF).State = EntityState.Modified
            End If

            For Each wfa In WF.Activities
                If wfa.ID > 0 Then
                    ctx.Entry(wfa).State = EntityState.Modified
                End If
            Next

            If WF.Customer.ID > 0 Then
                ctx.Entry(WF.Customer).State = EntityState.Modified
            End If

            ctx.SaveChanges()
        End Using


    Catch ex As Exception

    End Try
End Function

插入新实体可以正常工作。但是在此过程中第二次使用相同的 WF 对象进行更新时出现以下错误:

保存不为其关系公开外键属性的实体时发生错误。EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。有关详细信息,请参阅 InnerException。

错误在哪里?

4

1 回答 1

0

这发生在我身上一次。我想我只是通过暴露 EF 要求的键来解决它(暴露键意味着持有引用的实体也有一个包含外键的属性)例如:

public class Holder
{
    public Held HeldObject{get;set;}
    public int HeldID //this is the primary key for the entity Held (exact same name)
}

这将在数​​据库中创建一个 FK 限制

于 2012-11-13T17:07:20.860 回答