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.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
2 years ago

[…] Entity Framework core is an ORM tool available for.Net core applications. However, this is not the continuation of an Entity Frmework series. It is the separate project itself. With lot more modular approach and support of multiple databases like MySql, SqlLite, and InMemory.  InMemory database is quite helpful for writing test cases, also at the time of the development phase. […]

trackback
2 years ago

[…] Entity Framework core is an ORM tool available for.Net core applications. However, this is not the continuation of an Entity Frmework series. It is a separate project itself. With a lot more modular approach and support of multiple databases like MySql, SqlLite, and InMemory.  InMemory database is quite helpful for writing test cases, also at the time of the development phase. […]

trackback
1 year ago

[…] Value objects are nothing but, complex objects in Entity Framework. On a High-level comparison, I will say Entities have an Id property while Value objects do not have an Id property, it purely relies on all the properties available in the class. You can mark the value object by using attributes or fluent API in EF Core. […]