Auditing in Entity Framework.

Posted by Gabriel Susai on Stack Overflow See other posts from Stack Overflow or by Gabriel Susai
Published on 2009-09-03T17:43:25Z Indexed on 2010/05/24 21:01 UTC
Read the original article Hit count: 332

Filed under:
|
|

After going through Entity Framework I have a couple of questions on implementing auditing in Entity Framework.

I want to store each column values that is created or updated to a different audit table.

  1. Rightnow I am calling SaveChanges(false) to save the records in the DB(still the changes in context is not reset). Then get the added | modified records and loop through the GetObjectStateEntries. But don't know how to get the values of the columns where their values are filled by stored proc. ie, createdate, modifieddate etc.

  2. Below is the sample code I am working on it.

//Get the changed entires( ie, records)

  IEnumerable<ObjectStateEntry> changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);

        //Iterate each ObjectStateEntry( for each record in the update/modified collection)
        foreach (ObjectStateEntry entry in changes)
        {
            //Iterate the columns in each record and get thier old and new value respectively
            foreach (var columnName in entry.GetModifiedProperties())
            {
                string oldValue = entry.OriginalValues[columnName].ToString();
                string newValue = entry.CurrentValues[columnName].ToString();

                //Do Some Auditing by sending entityname, columnname, oldvalue, newvalue
            }

        }

        changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added);

        foreach (ObjectStateEntry entry in changes)
        {
            if (entry.IsRelationship) continue;
            var columnNames = (from p in entry.EntitySet.ElementType.Members
                               select p.Name).ToList();

            foreach (var columnName in columnNames)
            {
                string newValue = entry.CurrentValues[columnName].ToString();

                //Do Some Auditing by sending entityname, columnname, value
            }
        }

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about entity-framework