EF ObjectStateEntry OriginalValues contains CurrentValues

Carel

I am trying to override Entity Framework's SaveChanges() method to save auditing information. I begin with the following:

public override int SaveChanges()
{
    ChangeTracker.DetectChanges();
    ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;
    List<ObjectStateEntry> objectStateEntryList = ctx.ObjectStateManager.GetObjectStateEntries(
                                                         EntityState.Added
                                                       | EntityState.Modified
                                                       | EntityState.Deleted).ToList();

    foreach (ObjectStateEntry entry in objectStateEntryList)
    {
        if (!entry.IsRelationship)
        {
            //Code that checks and records which entity (table) is being worked with
            ...

            foreach (string propertyName in entry.GetModifiedProperties())
            {
                DbDataRecord original = entry.OriginalValues;
                string oldValue = original.GetValue(original.GetOrdinal(propertyName)).ToString();

                CurrentValueRecord current = entry.CurrentValues;
                string newValue = current.GetValue(current.GetOrdinal(propertyName)).ToString();

                if (oldValue != newValue)
                {
                    AuditEntityField field = new AuditEntityField
                    {
                        FieldName = propertyName,
                        OldValue = oldValue,
                        NewValue = newValue,
                        Timestamp = auditEntity.Timestamp
                    };
                    auditEntity.AuditEntityField.Add(field);
                }
            }
        }
    }
}

Problem I'm having is that the values I get in entry.OriginalValues and in entry.CurrentValues is always the new updated value:

Audit Entity State

Carel

The problem has been found:

public ActionResult Edit(Branch branch)
{
    if (ModelState.IsValid)
    {
        db.Entry(branch).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(branch);
}

Saving an update in the above way seems to cause the ChangeTracker to not pick up the old values. I fixed this by simply making use of ViewModels for all the required updates:

public ActionResult Edit(BranchViewModel model)
{
    if (ModelState.IsValid)
    {
        Branch branch = db.Branch.Find(model.BranchId);

        if (branch.BranchName != model.BranchName)
        {
            branch.BranchName = model.BranchName;
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    return View(model);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Entity framework EF.Functions.Like vs string.Contains

From Java

Ef core: Sequence contains no element when doing MaxAsync

From Dev

Extracting a complex type from entry.CurrentValues

From Dev

ICollection<>.Contains in EF as HashSet fails

From Dev

EF6 - using Contains with a list

From Dev

EF 6 OriginalValues lost when using Attach method

From Dev

EF 6.1 Sequence Contains more then one element

From Dev

Sequence contains more than one element error in EF CF Migrations

From Dev

ArrayList contains

From Dev

Multiple run time errors on querying records with EF using contains

From Dev

EF code-first: Sequence contains more than one matching element

From Dev

EF LINQ spatial query times out using Contains() method in SQL Server

From Dev

Failed to save data using EF6. Error: OriginalValues cannot be used for entities in the Added state

From Dev

EF6 How to query where children contains all values of a list

From Dev

Optimize EF query using Any instead of contains

From Dev

Use .Contains() in EF 6

From Dev

Possible SQL Injection when using contains with EF?

From Dev

EF Core query using String.Contains

From Dev

.Contains() in .Where() EF Core doesn't work .NET Core 3.1.8

From Dev

EF and CheckboxFor

From Dev

Not able to retrieve OriginalValues in Entity Framework 5

From Dev

EF 6 delete fails with The select list for the Insert statement contains more items than the insert list

From Dev

EF6 - using Contains with a list

From Dev

EF 6 OriginalValues lost when using Attach method

From Dev

EF LINQ spatial query times out using Contains() method in SQL Server

From Dev

EF 6 (exception) Sequence contains more than one element - Inserting new record

From Dev

EF7 / Linq - "Contains" query with nested object throws Exception

From Dev

EF Core MySQL Contains(variable) like operator

From Dev

Member 'CurrentValues' cannot be called for the entity of type 'MyTable' because the entity does not exist in the context

Related Related

  1. 1

    Entity framework EF.Functions.Like vs string.Contains

  2. 2

    Ef core: Sequence contains no element when doing MaxAsync

  3. 3

    Extracting a complex type from entry.CurrentValues

  4. 4

    ICollection<>.Contains in EF as HashSet fails

  5. 5

    EF6 - using Contains with a list

  6. 6

    EF 6 OriginalValues lost when using Attach method

  7. 7

    EF 6.1 Sequence Contains more then one element

  8. 8

    Sequence contains more than one element error in EF CF Migrations

  9. 9

    ArrayList contains

  10. 10

    Multiple run time errors on querying records with EF using contains

  11. 11

    EF code-first: Sequence contains more than one matching element

  12. 12

    EF LINQ spatial query times out using Contains() method in SQL Server

  13. 13

    Failed to save data using EF6. Error: OriginalValues cannot be used for entities in the Added state

  14. 14

    EF6 How to query where children contains all values of a list

  15. 15

    Optimize EF query using Any instead of contains

  16. 16

    Use .Contains() in EF 6

  17. 17

    Possible SQL Injection when using contains with EF?

  18. 18

    EF Core query using String.Contains

  19. 19

    .Contains() in .Where() EF Core doesn't work .NET Core 3.1.8

  20. 20

    EF and CheckboxFor

  21. 21

    Not able to retrieve OriginalValues in Entity Framework 5

  22. 22

    EF 6 delete fails with The select list for the Insert statement contains more items than the insert list

  23. 23

    EF6 - using Contains with a list

  24. 24

    EF 6 OriginalValues lost when using Attach method

  25. 25

    EF LINQ spatial query times out using Contains() method in SQL Server

  26. 26

    EF 6 (exception) Sequence contains more than one element - Inserting new record

  27. 27

    EF7 / Linq - "Contains" query with nested object throws Exception

  28. 28

    EF Core MySQL Contains(variable) like operator

  29. 29

    Member 'CurrentValues' cannot be called for the entity of type 'MyTable' because the entity does not exist in the context

HotTag

Archive