In this tutorial, we will understand, how you can handle the entity framework audit fields. No need to write the same lines of code again and again for entity framework created date modified date.

First of all, what is entity framework created date and Modified date, when we use this?

Keeping CreatedDate, ModifiedDate,  CreatedBy, and ModifiedBy or you can say entity framework audit fields columns in the database tables is part of good practices for database design.

These columns help in many scenarios like select all the record by created date, Modified date, created by and modified by. So when you find the unwanted data in the table, you can easily figure out the culprit. who created this, when it was created or updated.

If you have any transaction tables, like CustomerInfo, OrderDetails and Transactions then you can use CreatedDate and ModifiedDate.

User action fields also required auditing columns

If you have any tables which have user action like Order is placed by this user and modified by. In these kinds of scenario, you can use all four columns CreatedDate, ModifiedDate,  CreatedBy, and ModifiedBy.

I have taken an example of a simple Employee class. This class has a few fields like ID and Name along with auditing fields.

Public class Employee
{
  public int ID{get;set;}

  public String Name {get;set;}

  public String CreatedDate {get;set;}
  public String ModifiedDate{get;set;}
  public String CreatedBy{get;set;}
  public String ModifiedBy{get;set;}
}

While adding or updating the employee class in the database, you have to take care of these auditing properties. because we can not provide these properties in the user form as input fields.

Note: If you have one or two classes then you can manage to add additional code without any issue but if you have thousands of classes then obviously you will think of some generic code which can handle these two properties automatically while doing all add or edit operation.

All the tables in the database might not require the auditing information. Hence, Let’s create BaseClass for those entities who need auditing columns, not every class will inherit this class.

public class BaseClass
{

  public String CreatedDate {get;set;}
  public String ModifiedDate{get;set;}
  public String CreatedBy{get;set;}
  public String ModifiedBy{get;set;}
}

There are two advantages of using BaseClass here

  • No need to write auditing columns properties in all the entity classes
  • It will be easy to differentiate between the Auditing entity vs normal entity class

Overriding SaveChanges method will help us to centralize the code

In the Entity Framework, we can override the SaveChanges method inside the DbContext class. In the overridden method we can perform our auditing columns logic.

  public override int SaveChanges()
       {
    var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
           var currentUsername = HttpContext.Current != null && HttpContext.Current.User != null
                ? HttpContext.Current.User.Identity.Name
                : "Anonymous";
 foreach (var entity in entities)
        {
           if (entity.State == EntityState.Added)
              {
                    ((BaseEntity)entity.Entity).CreatedDate = DateTime.Now;
                    ((BaseEntity)entity.Entity).CreatedBy = currentUsername;
                }

                ((BaseEntity)entity.Entity).ModifiedDate = DateTime.Now;
                ((BaseEntity)entity.Entity).ModifiedBy = currentUsername;
            }
 return base.SaveChanges();
      }

Was this article helpful for you? Feel free to provide your comments and concerns in the below comments section.

Close

About The Author

Deependra Kushwah
Deependra kushwah is a member of the fastest growing bloggers community "betechnical", Author, Youtuber, and hardcore Coder. I love writing code in different languages, I also write blogs on tech tutorials, gadgets review and also post some technical videos on youtube on many topics.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.