Shadow Properties In Entity Framework Core

In this article, you will learn about shadow properties in Entity Framework Core.

Entity Framework Core is the most commonly used ORM in .NET Core applications. It is a lightweight, extensible, open source, and cross-platform version of the popular Entity Framework data access technology. One of the features in EF Core is Shadow Properties. In this article, we shall look into Shadow Properties in EF Core.

Shadow properties are properties that are not defined in your .NET entity class but are defined for that entity type in the EF Core model. This means that we can have columns for these properties in our tables, but we will not have a corresponding property field in our entity class. This is really helpful while designing our domain models as this helps to avoid unnecessary fields from the domain models which don't add any value to our domain logic but are required in our database.

One of the most common usages I see for Shadow Properties is audit fields that we commonly use in our domain models. We usually use fields like CreatedOn, LastModifiedOn, etc in our entities to store audit information.

These fields really don't provide much value to our domain but are actually useful. So removing these fields from our entities will make our domain model cleaner and by using Shadow Properties we can make these columns in the database too.

We shall be creating a .NET Core Web API project to learn Shadow Properties. I shall be using .NET CLI and Visual Studio Code for development. But the same can be developed using Visual Studio.

  • Create a folder and name it EFCoreShadowProperty and open VS Code from this directory.
  • Open the terminal and run the command - dotet new webapi --name EFCoreShadowProperty. This shall create a Web API project.
  • Add a new folder called Models. Let's add some model classes in this folder.
  • Add a class called Employee.
  1. namespace EFCoreShadowProperty.Models  
  2. {  
  3.     [Auditable]  
  4.     public class Employee  
  5.     {  
  6.         public int Id { getset; }  
  7.         public string Name { getset; }  
  8.         public int Age { getset; }  
  9.     }  
  10. }  
Add another class Department,
  1. namespace EFCoreShadowProperty.Models  
  2. {  
  3.     [Auditable]  
  4.     public class Department  
  5.     {  
  6.         public int Id { getset; }  
  7.         public string Name { getset; }  
  8.     }  
  9. }  
You may notice that I have decorated both the classes with a custom attribute named [Auditable]. This attribute will be used by the EF Core DBContext to add our shadow properties while creating the database. We will be overriding the OnModelCreating method of DBContext to add the fields CreatedOn and LastModifiedOn on the entities which are decorated with this attribute. We will also override the SaveChanges method of DBContext to add the current timestamp values on these fields if the entity is decorated with this attribute. The implementation of AuditableAttribute is given below. 
  1. using System;  
  2.   
  3. namespace EFCoreShadowProperty.Models  
  4. {  
  5.     [AttributeUsage(AttributeTargets.Class)]  
  6.     public class AuditableAttribute : Attribute   
  7.     {  
  8.     }  
  9. }  
Now, let's add our DBContext class. Create a class named EmployeeContext and add the following code.
  1. using System;  
  2. using System.Linq;  
  3. using System.Reflection;  
  4. using EFCoreShadowProperty.Models;  
  5. using JetBrains.Annotations;  
  6. using Microsoft.EntityFrameworkCore;  
  7.   
  8. namespace EFCoreShadowProperty  
  9. {  
  10.     public class EmployeeContext : DbContext  
  11.     {  
  12.         public DbSet<Employee> Employees { getset; }  
  13.         public DbSet<Department> Departments { getset; }  
  14.   
  15.         public EmployeeContext(DbContextOptions options) : base(options) { }  
  16.   
  17.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  18.         {  
  19.             foreach (var entityType in modelBuilder.Model.GetEntityTypes())  
  20.             {  
  21.                 if (entityType.ClrType.GetCustomAttributes(typeof(AuditableAttribute), true).Length > 0)  
  22.                 {  
  23.                     modelBuilder.Entity(entityType.Name).Property<DateTime>("CreatedOn");  
  24.                     modelBuilder.Entity(entityType.Name).Property<DateTime>("LastModifiedOn");  
  25.                 }  
  26.             }  
  27.   
  28.             base.OnModelCreating(modelBuilder);  
  29.         }  
  30.   
  31.         public override int SaveChanges()  
  32.         {  
  33.             ChangeTracker.DetectChanges();  
  34.             var timestamp = DateTime.Now;  
  35.   
  36.             foreach (var entry in ChangeTracker.Entries()  
  37.                     .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified))  
  38.             {               
  39.                 if (entry.Entity.GetType().GetCustomAttributes(typeof(AuditableAttribute), true).Length > 0)  
  40.                 {  
  41.                     entry.Property("LastModifiedOn").CurrentValue = timestamp;  
  42.   
  43.                     if (entry.State == EntityState.Added)  
  44.                     {  
  45.                         entry.Property("CreatedOn").CurrentValue = timestamp;  
  46.                     }  
  47.                 }  
  48.             }  
  49.             return base.SaveChanges();  
  50.         }  
  51.     }  
  52. }  
  • In the DBContext class we are overriding both the OnModelCreating and SaveChangesmethods.
  • In the OnModelCreating method, we loop through all the entities registered in the DBContext and use reflection to check whether the entity is applied with Auditableattribute and if it is applied then add the properties CreatedOn and LastModifiedOn to that entity.
  • We use a similar approach to the SaveChanges method also. Here, we will loop through all the entries in the ChangeTracker and use reflection to check whether the entity is applied with Auditable attribute and if it is applied, we set the current timestamp to LastModifiedOnproperty. If the state is EntityState.Added, we set the CreatedOn property with the current timestamp.
  • Now, let's add the migration. Open the terminal and run the following command - dotnet ef migrations add AuditFieldShadowProperty
  • After the migrations are created run the following command in the terminal - dotnet ef database update. This shall create the database for you with the tables.
Now, let's create a Web API to wire up the database we created. Add the following code in the ConfigureServices method in the Startup.cs class. Add your connection string in the appsettings.json file.
  1. services.AddDbContext<EmployeeContext>(opts =>  
  2. {  
  3.     opts.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]);  
  4. });  
Add a new controller class named EmployeesController. Add the following code in the controller.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using EFCoreShadowProperty.Models;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using Microsoft.EntityFrameworkCore;  
  8.   
  9. namespace EFCoreShadowProperty.Controllers  
  10. {  
  11.     [Route("api/[controller]")]  
  12.     [ApiController]  
  13.     public class EmployeesController : ControllerBase  
  14.     {  
  15.         private readonly EmployeeContext _employeeContext;  
  16.   
  17.         public EmployeesController(EmployeeContext employeeContext)  
  18.         {  
  19.             this._employeeContext = employeeContext;  
  20.         }  
  21.   
  22.         [HttpGet]  
  23.         [Route("{id}", Name = "Get")]  
  24.         public ActionResult<string> Get(int id)  
  25.         {  
  26.             var employee = _employeeContext.Employees  
  27.                 .Where(e => e.Id == id)  
  28.                 .Select(e => new  
  29.                 {  
  30.                     Id = e.Id,  
  31.                         Age = e.Age,  
  32.                         Name = e.Name,  
  33.                         CreatedOn = EF.Property<DateTime>(e, "CreatedOn"),  
  34.                         LastModifiedOn = EF.Property<DateTime>(e, "LastModifiedOn")  
  35.                 });  
  36.   
  37.             return Ok(employee);  
  38.         }  
  39.   
  40.         [HttpPost]  
  41.         public ActionResult Post([FromBody] Employee employee)  
  42.         {  
  43.             _employeeContext.Employees.Add(employee);  
  44.             _employeeContext.SaveChanges();  
  45.             return CreatedAtRoute("Get"new { id = employee.Id }, employee);  
  46.         }  
  47.   
  48.         [HttpPut("{id}")]  
  49.         public ActionResult Put(int id, [FromBody] Employee employee)  
  50.         {  
  51.             var employeeFromDb = _employeeContext.Employees.SingleOrDefault(e => e.Id == id);  
  52.             employeeFromDb.Age = employee.Age;  
  53.             employeeFromDb.Name = employee.Name;  
  54.             _employeeContext.SaveChanges();  
  55.             return Ok();  
  56.         }  
  57.     }  
  58. }  
The controller class contains three actions. The Post method will accept an Employee object and saves it in the database. Since we have overridden the SaveChanges method to set the Shadow Properties with the current timestamp this API will set those values in the database. The Put method accepts an id and an employee object as the parameter. This method will update the existing employee record in the database corresponding to the id with the input values. In this case, only the LastModifiedOn shadow property will be updated.
 
The Get method fetches the employee record from the database corresponding to the id supplied. You can see that I have used the static Property method of the EF utility class to fetch the Shadow Property values in the query.
  1. var employee = _employeeContext.Employees  
  2.                 .Where(e => e.Id == id)  
  3.                 .Select(e => new  
  4.                 {  
  5.                     Id = e.Id,  
  6.                         Age = e.Age,  
  7.                         Name = e.Name,  
  8.                         CreatedOn = EF.Property<DateTime>(e, "CreatedOn"),  // Querying Shadow Property  
  9.                         LastModifiedOn = EF.Property<DateTime>(e, "LastModifiedOn"// Querying Shadow Property  
  10.                 });  

Summary

In this article we looked at Shadow Properties in EF Core. We have also developed a simple Web API application which uses Shadow Properties for storing the audit field values in the database.