Entity Framework Created, Modified Date, Set Automatically | 2022

In this article, we will show the example of auto-populating the fields of auditing such as created date, modified date, CreatedBy & UpdatedBy using ef(entity framework). So, anywhere in our application, we do not have to write the same line of code.

Audit Columns in the Database

Auditing columns are the fields that take care of keeping track of each record when it was created, modified, and who created this record and modified by whom.

This helps to filter the data in big datasets and also can be very useful while generating the reports.

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

select all the records 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 scenarios, you can use all four columns CreatedDate, ModifiedDate,  CreatedBy, and modified by.

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 that can handle these two properties automatically while doing all add or edit operation.

All the tables in the database might not require 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.

Comments are closed.

Scroll to Top