2012-07-20 97 views
1

我有以下實體:EF代碼第一:更新實體

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。

錯誤在哪裏?

+0

類似的問題[here](http://stackoverflow.com/questions/5936880/ef-code-first-4-1-how-to-configure-one-to-many-relationship-with -默認)。 – neizan 2012-07-20 14:41:24

+0

什麼是InnerException? – Slauma 2012-07-20 15:14:52

回答

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限制在DB