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.
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.
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.
Was this article helpful for you? Feel free to provide your comments and concerns in the below comments section.