Entity Framework DbContext SaveChanges() OriginalValue Incorrect

Я пытаюсь реализовать AuditLog с помощью EF 4.1, переопределяя метод SaveChanges(). как обсуждалось в следующих местах:

Однако у меня возникают проблемы с «измененными» записями. Всякий раз, когда я пытаюсь получить OriginalValue рассматриваемого свойства, оно всегда имеет то же значение, что и в поле CurrentValue.

Я впервые использую этот код, и он успешно идентифицирует измененные записи:

public int SaveChanges(string userID)
{

    // Have tried both with and without the following line, and received same results:
    // ChangeTracker.DetectChanges();

    foreach (
      var ent in this.ChangeTracker
                     .Entries()
                     .Where(p => p.State == System.Data.EntityState.Added
                                     p.State == System.Data.EntityState.Deleted             
                                     p.State == System.Data.EntityState.Modified))
    {
        // For each change record, get the audit record entries and add them
        foreach (AuditLog log in GetAuditRecordsForChange(ent, userID))
        {
            this.AuditLog.Add(log);
        }

    }

    return base.SaveChanges();
}

Проблема в этом (сокращенный код):

    private List GetAuditRecordsForChange(DbEntityEntry dbEntry, string userID)
    {
        if (dbEntry.State == System.Data.EntityState.Modified)
        {
            foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
            {
                if (!object.Equals(dbEntry.OriginalValues.GetValue(propertyName),
                    dbEntry.CurrentValues.GetValue(propertyName)))
                {
                        // It never makes it into this if block, even when
                        //    the property has been updated.
                }

                // If I updated the property "Name" which was originally "OldName" to the value "NewName" and then break here and inspect the values by calling:
                //      ?dbEntry.OriginalValues.GetValue("Name").ToString()

                // the result will be "NewName" and not "OldName" as expected
             }
         }
    }

Странно то, что вызов dbEntry.Property( propertyName).IsModified(); будет вернуть true в этом случае. Просто внутри OriginalValue нет ожидаемого значения. Кто-нибудь готов помочь указать мне в правильном направлении? Кажется, я не могу заставить это работать правильно.

7
задан Community 23 May 2017 в 12:00
поделиться