Click here to Skip to main content
11,928,740 members (54,484 online)
Click here to Skip to main content
Add your own
alternative version


40 bookmarked

Implementing Audit Trail using Entity Framework - Part 2

, 1 Apr 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Implementing Audit Trail using Entity Framework's caching entries

Click to enlarge image


In Part 1, I talked about creating audit trail objects using the object state entries. As I said earlier, in the second part I will talk about roll back feature of this audit trail. In the first part, I already described that to get the Rollback feature from that audit trail, we have to consider some issues. We have to maintain the order of entity graph while inserting and deleting. That means the root entity has been inserted before the children and during deletion, we have to reverse it. The most important issue is that we have to make sure that each audit trail entry has been inserted according to this order. So during insertion of object, we also need to consider these things: 

  1. Maintain insertion date-time to sort the audit trial
  2. Store the old data and new data
  3. Store the state of the data as audit action

If user chooses a certain time to roll back, we have to start with last audits and do the roll back action for each audit till a certain time. So now the question is what the roll back action will be. You can guess that it’s depending on the Audit action of each entity. During rollback:

  1. Inserted data will be deleted.
  2. Deleted data will be inserted.
  3. Modified data will be replaced by the old one.

If we see the conceptual model, our Entity set for Audit was:

Here “RevisionStamp” holds the audit insertion date-time, Actions hold the audit action of the entity object (Insert/deleted/modified). Other properties describe themselves with their names.

So here “Deleted” and “Modified” objects will be rolled back with “Old data” property. And Inserted data will be rolled back with “New data” property.   

Using the Code


So first, I am going to retrieve all the audits that happen after a specific date-time. This specific date-time is taken from the user. What we have to do is, rollback action for each audit till a specific date and we have to start with the last one (bottom to top). That is why we are going to sort the audit with “RevisionStamp” in a descending order and start doing rollback.

public static bool RollBack(DateTime rollBackDate, string userName)
    using (TransactionScope transactionScope = 
	new TransactionScope(System.Transactions.TransactionScopeOption.Required, 
        AdventureWorksEntities context =new AdventureWorksEntities();
            if (context.Connection.State != ConnectionState.Open)
            {//Open the connection
            }//end if 
            //find all audits to roll back
            IEnumerable<DBAudit> auditsToRollBack = DataAdapter.GetEntity
			<DBAudit>(context, a => a.RevisionStamp >= rollBackDate );
             if (null != auditsToRollBack && auditsToRollBack.Count() > 0)
            {//if any data found to roll back
                //Order by the audits by creation datetime
                IEnumerable<DBAudit> orderedAudits = 
		auditsToRollBack.OrderByDescending(a => a.RevisionStamp);
                 foreach (var audit in orderedAudits)
                {//iterate each audit 
                    AuditTrailHelper.DoRollBackAction(ref context, audit, userName);
                }//end foreach
                int i =context.SaveChanges();
                if (i > 0)
                    return true;
        catch (Exception ex)
            throw ex;
            // Explicitly dispose of the context, 
            // which closes the connection. 
    return false;

In DoRollBackAction as I said before, “Deleted” and “Modified” objects will be rolled back with “Old data” property. And Inserted data will be rolled back with “New data” property.

As I stored old data and new data with XML Serialization while creating the Audit object, I have to deserialise that data into “EntityObject” and do the reverse action according to the audit action.

private static void DoRollBackAction
   (ref AdventureWorksEntities context,  DBAudit auditInfo, string userName)
           if (auditInfo.Actions == AuditTrailHelper.AuditActions.U.ToString() ||
       auditInfo.Actions == AuditTrailHelper.AuditActions.D.ToString())
           {//For action of Update and Delete
               //Deserialized old data from the XML
               object oldData = AuditTrailHelper.GetAuditObjectFromXML
               (auditInfo.OldData, auditInfo.TableName);

               if (oldData is EntityObject)
                   EntityObject oldEntity = (EntityObject)oldData;
                   oldEntity.EntityKey = null;
                   //add in case of delete or edit the current one with old data
                   DataAdapter.EditEntity(ref context, oldEntity);
           else if (auditInfo.Actions == AuditTrailHelper.AuditActions.I.ToString())
           {//For Insert Action
               object newData = AuditTrailHelper.GetAuditObjectFromXML
               (auditInfo.NewData, auditInfo.TableName);

               if (newData is EntityObject)
                   //Otherwise, delete the entity that has been inserted before
                   EntityObject newEntity = (EntityObject)newData;
                   newEntity.EntityKey = null;
                   EntityKey key = context.CreateEntityKey
               (newEntity.GetType().Name, newEntity);

                   object objToRemoved = null;
                   if (context.TryGetObjectByKey(key, out objToRemoved))
                   {//delete the entity
                   }//end if
           //delete the audit

After serializing the entity Object, we get the XML string like this:

<SalesOrderDetail xmlns:xsi= 
  <SalesOrderHeaderReference />
          <Value xsi:type="xsd:int">1</Value>
          <Value xsi:type="xsd:int">777</Value>

I have to deserialize this XML string. During deserializing, I have created an XML document and an XML reader using that document. Using that reader, I deserialized the entity object. The method to deserialize the entityobject is:

public static object GetAuditObjectFromXML(string ObjectInXML, string typeName)
    XDocument doc = XDocument.Parse(ObjectInXML);
    //Assuming doc is an XML document containing a 
    //serialized object and objType is a System.Type set to the type of the object.
    XmlReader reader = doc.CreateReader();
    //get the Type of entity object  
    Type entityType = Assembly.GetExecutingAssembly().GetType
			("ImplAuditTrailUsingEF." + typeName);
     XmlSerializer ser = new XmlSerializer(entityType);
    return ser.Deserialize(reader);

For inserting deleted object or to change back modified object, I wrote a single method to edit the object:

EditEntity(ref AdventureWorksEntities context, EntityObject entity)

Is this method, I change the existence object and attach it to the container otherwise I have inserted the entityObject into the context. To save all of this change, we need an entry in Object state cache. 

    public static void EditEntity
	(ref AdventureWorksEntities context, EntityObject entity)
        // Define an ObjectStateEntry and EntityKey for the current object.
        EntityKey key;
        object originalItem;
        // Get the detached object's entity key.
        if (entity.EntityKey == null)
            // Get the entity key of the updated object.
            key = context.CreateEntityKey(entity.GetType().Name, entity);
            key = entity.EntityKey;
            // Get the original item based on the entity key from the context
            // or from the database.
            if (context.TryGetObjectByKey(key, out originalItem))
            {//accept the changed property
                 // Call the ApplyPropertyChanges method to apply changes
                // from the updated item to the original version.
                    key.EntitySetName, entity);                    
            {//add the new entity
                context.AddObject(entity.GetType().Name, entity);
            }//end else
        catch (System.Data.MissingPrimaryKeyException ex)
            throw ex;
        catch (System.Data.MappingException ex)
            throw ex;
        catch (System.Data.DataException ex)
            throw ex;

That is all for implementing rollback mechanism in our audit trail. Now all we have to do is just call the “RollBack” method and give it a specific date to roll back.

private void btnRollBack_Click(object sender, RoutedEventArgs e)
    if (AuditTrailHelper.RollBack(dtpRollBackDate.SelectedDate.Value, "Admin"))
        MessageBox.Show("Successfully Roll Backed!!");

That’s all for implementation of Audit trial with entity framework. Here I have deleted the audits which have been rolled back. Definitely each rollback operation is also a DB operation and I did an audit for each rollback operation.   

Is the sample project, I have used the free version of Xeed. You may need to download that Library, otherwise you can replace it with the WPF toolkit. It has just been used for getting a date-time from user to rollback. 


  • 1st April, 2009: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Morshed Anwar
Team Leader Adaptive Enterprise Limited (
Bangladesh Bangladesh
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionSequence contains no elements Pin
Member 831715423-Apr-13 19:41
memberMember 831715423-Apr-13 19:41 
AnswerRe: Sequence contains no elements Pin
Morshed Anwar24-Apr-13 6:49
memberMorshed Anwar24-Apr-13 6:49 
GeneralRe: Sequence contains no elements Pin
Member 831715424-Apr-13 22:19
memberMember 831715424-Apr-13 22:19 
GeneralRe: Sequence contains no elements Pin
Morshed Anwar25-Apr-13 1:17
memberMorshed Anwar25-Apr-13 1:17 
GeneralRe: Sequence contains no elements Pin
Member 831715425-Apr-13 3:06
memberMember 831715425-Apr-13 3:06 
GeneralRe: Sequence contains no elements Pin
Morshed Anwar25-Apr-13 4:22
memberMorshed Anwar25-Apr-13 4:22 
GeneralMy vote of 5 Pin
Tridip Bhattacharjee10-May-12 21:31
memberTridip Bhattacharjee10-May-12 21:31 
QuestionRetrieve change data for a specific record. Pin
jabit22-Jun-11 9:30
memberjabit22-Jun-11 9:30 
GeneralGood work if you are doing audit from the front end Pin
Donsw3-May-09 12:32
memberDonsw3-May-09 12:32 
GeneralRe: Good work if you are doing audit from the front end Pin
Morshed Anwar4-May-09 0:56
memberMorshed Anwar4-May-09 0:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151126.1 | Last Updated 1 Apr 2009
Article Copyright 2009 by Morshed Anwar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid