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 that 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 named 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.
namespace EFCoreShadowProperty.Models
{
[Auditable]
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
Add another class Department,
namespace EFCoreShadowProperty.Models
{
[Auditable]
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
}
You may notice that I have decorated both 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 that 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.
using System;
namespace EFCoreShadowProperty.Models
{
[AttributeUsage(AttributeTargets.Class)]
public class AuditableAttribute : Attribute
{
}
}
Now, let's add our DBContext class. Create a class named EmployeeContext and add the following code.
using System;
using System.Linq;
using System.Reflection;
using EFCoreShadowProperty.Models;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
namespace EFCoreShadowProperty
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
public EmployeeContext(DbContextOptions options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (entityType.ClrType.GetCustomAttributes(typeof(AuditableAttribute), true).Length > 0)
{
modelBuilder.Entity(entityType.Name).Property<DateTime>("CreatedOn");
modelBuilder.Entity(entityType.Name).Property<DateTime>("LastModifiedOn");
}
}
base.OnModelCreating(modelBuilder);
}
public override int SaveChanges()
{
ChangeTracker.DetectChanges();
var timestamp = DateTime.Now;
foreach (var entry in ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified))
{
if (entry.Entity.GetType().GetCustomAttributes(typeof(AuditableAttribute), true).Length > 0)
{
entry.Property("LastModifiedOn").CurrentValue = timestamp;
if (entry.State == EntityState.Added)
{
entry.Property("CreatedOn").CurrentValue = timestamp;
}
}
}
return base.SaveChanges();
}
}
}

Keith FimreitePosted Aug 22, 2019, 12:53 AM
This is great but I REALLY would like to see how you would implement with CreatedBy and ModifiedBy and store the current user Id. I am trying to do that in my repo but I have been running into issues: https://github.com/enkodellc/blazorboilerplate
Sajith KPosted May 24, 2019, 3:24 AM
Very Informative
Mahesh ChandPosted May 22, 2019, 7:01 PM
Thank you, Geo.
Sarathlal SaseendranPosted May 22, 2019, 2:32 PM
Hi Geo, Informative article on shadow properties. Thanks for sharing.