Shadow properties in Entity framework core (EF 7)

Entity framework core introduces new feature known as shadow properties. Shadow properties are do not part of entity class, but treated as part of it. The value and state of these properties is maintained purely in the Change Tracker API. These properties can participate in all database operations, but should not be exposed via entity class to the rest of the application.

shadow properties

The main advantages of shadow properties are you can access it without declaring it as part of domain model and It allows developers to define properties in class which doesn't have source code for.

Let's take example of Employee, In database Employee table have five properties EmpoyeeId, FirstName, LastName, Age and CreatedDate. CreatedDate is not exposed and should be define as Shadow properties.

public class Employee
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

Currently, Shadow properties can not be created with data annotations. You can use the Fluent API to configure shadow properties. Shadow properties are defined by overriding OnModelCreating event in DbContext class.

Here is an example of attaching a DateTime property called CreatedDate to the Employee entity. CreatedDate properties state will be manage by change tracker API by it self.

protected override void OnModelCreating(ModelBuilder modelBuilder)

As Change tracker APIs are responsible to manage State of Shadow properties, Get and Set operations will be perform by Change tracker APIs. We can modify the value of shadow property.

context.Entry(employee).Property("CreatedDate").CurrentValue = DateTime.Now; 

Shadow properties can be referenced in LINQ queries via the EF.Property static method. For example, the following code can be used to retrieve employee list order by created date.

var employees = context.Employee
                       .OrderBy(b => EF.Property<DateTime>(b, "CreatedDate"));

On OnModelCreating event execution, If the name supplied to the Property method matches the name of an existing property (a shadow property or one defined on the entity class), then the code will configure that existing property rather than introducing a new shadow property.

Recently Devid Miller published Introductory video on shadow Properties in Entity Framework.

Image Credit : PetaPixel