出於審計原因,我重寫了SaveChanges函數。但是,我想捕捉原始對象(即人物)的原始值和當前值,以便我可以序列化前後兩者。從Entity Framework的SaveChanges函數獲取原始對象?
Public Overrides Function SaveChanges() As Integer
ChangeTracker.DetectChanges()
Dim ctx As ObjectContext = DirectCast(Me, IObjectContextAdapter).ObjectContext
Dim objectStateEntryList As List(Of ObjectStateEntry) = ctx.ObjectStateManager.
GetObjectStateEntries(EntityState.Added Or EntityState.Modified Or EntityState.Deleted).ToList()
For Each ent As ObjectStateEntry In objectStateEntryList
If Not ent.IsRelationship Then
Dim objectType As Type = ObjectContext.GetObjectType(ent.Entity.GetType)
Dim audit As New Audit With {
.ObjectId = ent.EntityKey.EntityKeyValues.First.Value,
.ObjectType = ObjectContext.GetObjectType(ent.Entity.GetType).Name,
.User = (From u In Users Where u.Username = My.User.Name).First
}
With audit
Select Case ent.State
Case EntityState.Added
.Action = "Created"
.Detail = "Record created"
Case EntityState.Deleted
.Action = "Deleted"
.Detail = "Record deleted"
Case EntityState.Modified
Dim newObj As String = SerializeToString(
Convert.ChangeType(ent.Entity, objectType)
)
.Action = "Modified"
.Detail = newObj.ToString
End Select
End With
End If
Next
Return MyBase.SaveChanges()
End Function
這就是我得到了多少,但當我嘗試和ChangeType它拋出「對象必須實現IConvertible」。
什麼是SerializeToString,它爲什麼關心你傳遞給它的類型?另外,爲什麼不爲你的序列化程序使用JSON.NET? –
@JonathanAllen這只是我使用XmlSerializer編寫的函數,然後將xml作爲字符串返回,以便我可以存儲它。我沒有使用JSON.NET,因爲我想將它作爲XML存儲。 –
啊,是的,那個老問題。我現在看到爲什麼你想要調用ChangeType,儘管它沒有做你認爲它的作用。 –