Entity Framework 5 - Why is Entity State “Modified” after PropertyValue is set back to Original

后端 未结 3 1879
长发绾君心
长发绾君心 2021-01-11 23:59

i use the EF5 and don\'t know why a entity has the state \"modified\" after i set the only changed PropertyValue of this entity back to the original value.

         


        
3条回答
  •  醉梦人生
    2021-01-12 00:33

    Building on User1481065's answer, to overcome the possibility of an exception if any of OriginalValues is null, try the below. I've assumed a context that may contain more than one entity that may have updates (which may not necessarily be actual changes in value).

    _dirty = False
    Dim oChanges As IEnumerable(Of DbEntityEntry(Of CsSetting)) = _dbContext.ChangeTracker.Entries(Of CsSetting)().Where(Function(r) r.State <> EntityState.Unchanged)
    For Each c As DbEntityEntry(Of CsSetting) In oChanges
        _dirty = c.OriginalValues.PropertyNames.Any(Function(n) (c.OriginalValues(n) Is Nothing And c.CurrentValues(n) IsNot Nothing) OrElse (c.OriginalValues(n) IsNot Nothing AndAlso Not c.OriginalValues(n).Equals(c.CurrentValues(n))))
        If _dirty Then Exit For
    Next c
    Return _dirty
    

    You may not need the loop and therefore the presetting of _dirty.

提交回复
热议问题