Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5954215
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T17:56:21+00:00 2026-05-22T17:56:21+00:00

I am trying to implement a constrained ‘audit log’ of property changes to a

  • 0

I am trying to implement a constrained ‘audit log’ of property changes to a properties in a set of classes. I have successfully found out how to set CreatedOn|ModifiedOn type properties, but am failing to find out how to ‘find’ the property that has been modified.

Example:

public class TestContext : DbContext
{
    public override int SaveChanges()
    {
        var utcNowAuditDate = DateTime.UtcNow;
        var changeSet = ChangeTracker.Entries<IAuditable>();
        if (changeSet != null)
            foreach (DbEntityEntry<IAuditable> dbEntityEntry in changeSet)
            {

                switch (dbEntityEntry.State)
                {
                    case EntityState.Added:
                        dbEntityEntry.Entity.CreatedOn = utcNowAuditDate;
                        dbEntityEntry.Entity.ModifiedOn = utcNowAuditDate;
                        break;
                    case EntityState.Modified:
                        dbEntityEntry.Entity.ModifiedOn = utcNowAuditDate;
                        //some way to access the name and value of property that changed here
                        var changedThing = SomeMethodHere(dbEntityEntry);
                        Log.WriteAudit("Entry: {0} Origianl :{1} New: {2}", changedThing.Name,
                                        changedThing.OrigianlValue, changedThing.NewValue)
                        break;
                }
            }
        return base.SaveChanges();
    }
}

So, is there a way to access the property that changed with this level of detail in EF 4.1 DbContext?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T17:56:22+00:00Added an answer on May 22, 2026 at 5:56 pm

    Very, very rough idea:

    foreach (var property in dbEntityEntry.Entity.GetType().GetProperties())
    {
        DbPropertyEntry propertyEntry = dbEntityEntry.Property(property.Name);
        if (propertyEntry.IsModified)
        {
            Log.WriteAudit("Entry: {0} Original :{1} New: {2}", property.Name,
                propertyEntry.OriginalValue, propertyEntry.CurrentValue);
        }
    }
    

    I have no clue if this would really work in detail, but this is something I would try as a first step. Of course there could be more then one property which has changed, therefore the loop and perhaps multiple calls of WriteAudit.

    The reflection stuff inside of SaveChanges could become a performance nightmare though.

    Edit

    Perhaps it is better to access the underlying ObjectContext. Then something like this is possible:

    public class TestContext : DbContext
    {
        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges(); // Important!
    
            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)
               {
                   switch (entry.State)
                   {
                       case EntityState.Added:
                           // write log...
                           break;
                       case EntityState.Deleted:
                           // write log...
                           break;
                       case EntityState.Modified:
                       {
                           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) // probably not necessary
                               {
                                   Log.WriteAudit(
                                       "Entry: {0} Original :{1} New: {2}",
                                       entry.Entity.GetType().Name,
                                       oldValue, newValue);
                               }
                           }
                           break;
                       }
                   }
               }
           }
           return base.SaveChanges();
        }
    }
    

    I’ve used this myself in EF 4.0. I cannot find a corresponding method to GetModifiedProperties (which is the key to avoid the reflection code) in the DbContext API.

    Edit 2

    Important: When working with POCO entities the code above needs to call DbContext.ChangeTracker.DetectChanges() at the beginning. The reason is that base.SaveChanges is called too late here (at the end of the method). base.SaveChanges calls DetectChanges internally, but because we want to analyze and log the changes before, we must call DetectChanges manually so that EF can find all modified properties and set the states in the change tracker correctly.

    There are possible situations where the code can work without calling DetectChanges, for example if DbContext/DbSet methods like Add or Remove are used after the last property modifications are made since these methods also call DetectChanges internally. But if for instance an entity is just loaded from DB, a few properties are changed and then this derived SaveChanges is called, automatic change detection would not happen before base.SaveChanges, finally resulting in missing log entries for modified properties.

    I’ve updated the code above accordingly.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been trying to implement Win32's MessageBox using GTK. The app uses SDL/OpenGL,
We are trying to implement a REST API for an application we have now.
I'm trying to implement an identity map using generics. I have an abstract class,
All I am currently trying implement something along the lines of dim l_stuff as
trying to implement a dialog-box style behaviour using a separate div section with all
Am trying to implement a generic way for reading sections from a config file.
I am trying to implement string unescaping with Python regex and backreferences, and it
I'm trying to implement a data compression idea I've had, and since I'm imagining
I'm trying to implement something like this: <div> <table> <thead> <tr> <td>Port name</td> <td>Current
I am trying to implement a software Null Modem . Any suggestion how to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.