我有以下实体:
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 :(得分:0)
这件事发生在我身上。 我想我只是通过暴露EF要求的钥匙来解决它 (公开密钥意味着持有引用的实体也具有包含外键的属性) e.g:
public class Holder
{
public Held HeldObject{get;set;}
public int HeldID //this is the primary key for the entity Held (exact same name)
}
这将在DB
中创建FK限制