EF标记实体已修改,没有任何更改

时间:2016-06-01 14:10:37

标签: vb.net entity-framework

使用EF6.1.3中的代理和以下代码(VB.NET): -

Dim DB As New BMContext

Dim sl = DB.StockLevels.First
Dim ee = (From e In DB.ChangeTracker.Entries Where e.Entity Is sl).Single
sl.Level = sl.Level

在最后一行正确检查ee.State之前给出未修改状态。在该行之后,即使该属性已设置为已存在,它也显示为已修改。当我调用SaveChanges时,这甚至会触发UPDATE!

数据类代码: -

Public Class StockLevel
    Public Overridable Property ID As Integer
    Public Overridable Property Level As Integer?
End Class

显然,我的实际代码相当复杂,因为除了演示问题之外,这个例子毫无意义。

2 个答案:

答案 0 :(得分:1)

  

"更改跟踪代理会在写入任何值时将属性标记为已修改。"

来自source

基本上,由于您为此属性分配了一个值(即使它是完全相同的值),您将收到Modified状态。

答案 1 :(得分:0)

我最后在SaveChanges之前写了这个来打电话,虽然我觉得有点荒谬,我需要......

Public Class DbEntityModification

    Public ReadOnly Property FieldName As String
    Public ReadOnly Property OriginalValue As Object
    Public ReadOnly Property CurrentValue As Object

    Public Sub New(FieldName As String, OriginalValue As Object, CurrentValue As Object)
        _FieldName = FieldName
        _OriginalValue = OriginalValue
        _CurrentValue = CurrentValue
    End Sub

End Class

<Extension()> Public Function GetChangedValues(e As DbEntityEntry) As IDictionary(Of String, DbEntityModification)

    Dim ret As New Dictionary(Of String, DbEntityModification)

    For Each propname In e.CurrentValues.PropertyNames
        Dim nv = e.CurrentValues.Item(propname)
        Dim ov = e.OriginalValues.Item(propname)

        Dim Changed = False
        If ov Is Nothing Then
            Changed = nv IsNot Nothing
        ElseIf Not ov.Equals(nv) Then
            Changed = True
        End If

        If Changed Then
            Dim m As New DbEntityModification(propname, ov, nv)
            ret.Add(propname, m)
        End If

    Next
    Return ret
End Function

<Extension()> Public Sub MarkUnchangedAnyUnchangedEntities(ees As IEnumerable(Of DbEntityEntry))
    For Each ee In ees
        If ee.State = EntityState.Modified Then
            If GetChangedValues(ee).Keys.Count = 0 Then
                ee.State = EntityState.Unchanged
            End If
        End If
    Next
End Sub
<Extension()> Public Sub MarkUnchangedAnyUnchangedEntities(context As DbContext)
    context.ChangeTracker.Entries.MarkUnchangedAnyUnchangedEntities()
End Sub