【问题标题】:EF code first: update entityEF 代码优先:更新实体
【发布时间】:2012-11-14 01:07:20
【问题描述】:

我有以下实体:

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。

错误在哪里?

【问题讨论】:

标签: frameworks entity


【解决方案1】:

这件事发生在我身上一次。 我想我只是通过暴露 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 限制

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多