Introduction
In Entity Framework starting from version 4 and above we have the option to override the default “SaveChanges()” method and use some custom code or some business logic before committing the changes to the database. And this feature is very handy when we have entities with common properties that need to be handled automatically. We have encountered a few scenarios where we have entities with a modified date and modified by the user property that needs to be be updated correctly each time we deal with those entities. So rather than assigning a value to those properties every time throughout the application, what we can do is to have a single place with some logic written for the entities to populate the modified date and modified user name and than we can save the changes to the database. The scenario that I am talking about can be easily handled by overriding the “SaveChanges()” method of Entity Framework. Let's understand it with an example below.
Explanation
Let us say we have three entities named Employee, Department and Employment and they look something like:
- public class Department : EntityInformation
- {
- public int DepartmentID { get; set; }
- public string DepartmentName { get; set; }
- public string Location { get; set; }
-
- public virtual ICollection<Employment> Employments { get; set; }
- }
-
- public class Employee : EntityInformation
- {
- public int EmployeeID { get; set; }
- public string Name { get; set; }
- public int Age { get; set; }
-
- public virtual ICollection<Employment> Employments { get; set; }
- }
-
- public class Employment
- {
- public int EmploymentID { get; set; }
- public int EmployeeID { get; set; }
- public int DepartmentID { get; set; }
-
- public virtual Department Department { get; set; }
- public virtual Employee Employee { get; set; }
- }
And the common entity:
- public class EntityInformation
- {
- public DateTime ModifiedDate { get; set; }
- public string ModifiedUserName { get; set; }
- }
So both Employee and Department have the common property
“ModifiedDate” and
“ModifiedUserName”. Depending on the business we need to update the modified date and the user name each time we deal with these two entities. Either we are creating a new employee or department or we are updating an existing employee or department. In both cases we need to populate the current date in the
“ModifiedDate” column and the current user in the
“ModifiedUserName” column.
As stated earlier, here we will override the default “SaveChanges()” method of Entity Framework. Since we are overriding “SaveChanges()” our context class will look as in the following.
- public class OrganizationContext : DbContext
- {
- public OrganizationContext()
- : base("OrganizationContext")
- {
- }
-
- public DbSet<Employee> Employees { get; set; }
- public DbSet<Department> Departments { get; set; }
- public DbSet<Employment> Employments { get; set; }
-
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
- }
-
-
-
-
-
- public override int SaveChanges()
- {
- var selectedEntityList = ChangeTracker.Entries()
- .Where(x => x.Entity is EntityInformation &&
- (x.State == EntityState.Added || x.State == EntityState.Modified));
-
-
- var userName = "MUKESH";
-
- foreach (var entity in selectedEntityList)
- {
-
- ((EntityInformation)entity.Entity).ModifiedDate = DateTime.Now;
- ((EntityInformation)entity.Entity).ModifiedUserName = userName;
- }
-
- return base.SaveChanges();
- }
- }
Now let's analyze this
“SaveChanges()” method.
- var selectedEntityList = ChangeTracker.Entries()
- .Where(x => x.Entity is EntityInformation &&
- (x.State == EntityState.Added || x.State == EntityState.Modified));
We know that the context monitors the changed entities in the connection and we can get all the tracked entities using
“ChangeTracker.Entities()”. Now there can be n number of entities and all the entities will not necessarily have the common properties
“ModifiedDate” and
“ModifiedUserName” so we need to find the entities with the common properties, in other words we need to get the entities of type
“EntityInformation”. And in the last segment we are trying to get the entities that are in the modified and added state, there are other entity states also (deleted, detached and unchanged) but we are mainly concerned with these two (modified and added) entity states.
- foreach (var entity in selectedEntityList)
- {
-
- ((EntityInformation)entity.Entity).ModifiedDate = DateTime.Now;
- ((EntityInformation)entity.Entity).ModifiedUserName = userName;
- }
Now in the code above we are looping through all the tracked entities of type
“EntityInformation” with the entity state modified or added. And for each entity we are assigning
“ModifiedDate” and
“ModifiedUserName”.
- return base.SaveChanges();
And finally calling the
“SaveChanges()” method of the base class.
So now whenever you call
“SaveChanges()” with the entities of type
“EntityInformation” the
“ModifiedDate” and
“ModifiedUserName” will be handled automatically and will be populated for that entity.
I hope this will help!