Extend base type and automatically update audit information on Entity

Posted by Nix on Stack Overflow See other posts from Stack Overflow or by Nix
Published on 2010-04-06T21:39:40Z Indexed on 2010/04/13 11:43 UTC
Read the original article Hit count: 431

I have an entity model that has audit information on every table (50+ tables)

 CreateDate
 CreateUser
 UpdateDate
 UpdateUser

Currently we are programatically updating audit information.

Ex:

  if(changed){
        entity.UpdatedOn = DateTime.Now;
        entity.UpdatedBy = Environment.UserName;
        context.SaveChanges();
   }

But I am looking for a more automated solution. During save changes, if an entity is created/updated I would like to automatically update these fields before sending them to the database for storage.

Any suggestion on how i could do this? I would prefer to not do any reflection, so using a text template is not out of the question.

A solution has been proposed to override SaveChanges and do it there, but in order to achieve this i would either have to use reflection (in which I don't want to do ) or derive a base class. Assuming i go down this route how would I achieve this?

For example

EXAMPLE_DB_TABLE
 CODE
 NAME
 --Audit Tables
 CREATE_DATE
 CREATE_USER
 UPDATE_DATE
 UPDATE_USER

And if i create a base class

 public abstract class IUpdatable{

     public virtual DateTime CreateDate {set;}
     public virtual string CreateUser { set;}
     public virtual DateTime UpdateDate { set;}
     public virtual string UpdateUser { set;}
 }

The end goal is to be able to do something like...

   public overrride void SaveChanges(){
        //Go through state manager and update audit infromation
        //FOREACH changed entity in state manager
        if(entity is IUpdatable){
           //If state is created... update create audit.
           //if state is updated... update update audit
        }
   }

But I am not sure how I go about generating the code that would extend the interface.

© Stack Overflow or respective owner

Related posts about .net-3.5

Related posts about entity-framework