EF6 Code First: Mapping All Private Properties Using Custom Conventions

A while back I blogged about mapping to private properties with Code First. The approach shown in that post works with EF4.1 onwards but it requires you to explicitly configure every private property that you want included in your model. That’s going to get tiresome if you have a big model and want all private properties to be mapped.

In EF6 we’ve introduced a new feature called Custom Code First Conventions. This allows you to define some patterns/rules about how your model should be configured. These custom conventions are added inside the OnModelCreating method on your derived context – the same place you perform configuration via the Fluent API.

Note: The code in this post is written using EF6 Alpha 2, if you are using a later release you may need to adjust the code to reflect API changes.

Without further ado… here is a convention that will include all private properties in your model by default.

public class MyContext : DbContext
{
  // DbSets etc. defined here

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder
      .Entities()
      .Configure(c =>
        {
          var nonPublicProperties = c.ClrType.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance);

          foreach (var p in nonPublicProperties)
          {
            c.Property(p).HasColumnName(p.Name);
          }
        });
  }
}

The convention runs for all entities, finds any non-public properties and then configures them to ensure they are included in the model.

To have the property included in the model I need to perform some form of configuration – I’m choosing to call HasColumnName since it’s common to all property types and I can just pass in the name of the property. In the Fluent API, simply calling Property is enough to have the property included in the model. For the final release of EF6 we may update conventions to have the same logic – in which case the HasColumnName call could be removed.

I’ve written this convention using ‘lightweight conventions’, this part of the custom conventions feature allows you to build conventions using an API surface that looks and feels similar to the Code First Fluent API. For more information the different types of conventions you can write, check out the walkthrough and feature specification.