Entity Framework Core - Shadow Properties

One of the newest features in Entity Framework Core is Shadow Properties. Shadow Properties are fields which are not part of your entity class but exist only in the entity model. In this post, let’s figure out how to use shadow properties in Entity Framework Core and why they can be useful.

The first nuance that you will run into with Entity Framework is that EF will always ask for an ID field in each entity model. What do you do if you have a 3rd party extension and want to create and entity against their class dynamically?

Below is an example context that will do this. Override the OnModelCreating function of your Context. Run a for loop over each entity type. Notice by convention you can just add a field called “id” and Entity Framework Core will automatically create an id field with a primary key. This can save a bunch of time when you need to generate extras fields. After running this you will notice Class1 and Class2 will both have Id and SecondField added to their entity model.

public class ShadowContext : DbContext {

    public DbSet<Class1> Class1 { get; set; }
    public DbSet<Class2> Class2 { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
           modelBuilder.Entity(entityType.ClrType).Property<int>("Id");
           modelBuilder.Entity(entityType.ClrType).Property<string>("SecondField");
        }           
    }

}