EF6 Code First: Mapping All Private Properties Using Custom Conventions

Posted on January 23, 2013. Filed under: Entity Framework, Visual Studio | Tags: , , , , |

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.

About these ads

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

10 Responses to “EF6 Code First: Mapping All Private Properties Using Custom Conventions”

RSS Feed for RoMiller.com Comments RSS Feed

Hi Arthur!

cool!!

sorry……Rowan (no Arthur)

aggggggggggg!

No worries… hi :)

[...] may also want to check this interesting post on conventions from [...]

Hello Rowan, I noticed all your blogs are polluted by spam comments. It really makes a bad impression. After all you are one of the developpers that is in the spotlights as you are the face behind the Entity Framework team.

Thanks for the reminder… I just did another clean up. There seem to be a lot getting through the spam filter recently.

Here’s a similar example I wrote, which only maps non-public properties that include the [Column] attribute. This way you can select which properties to hide from EF, and which properties EF should bind to:

http://stackoverflow.com/a/21686896/605067

Neat, I really like how flexible the conventions feature turned out.

Mapping to a private property is not nearly as useful as mapping to a private field. The reason is that you wouldn’t want the setter function to execute validation logic during rehydration of an entity. Therefore, this really isn’t all that useful. NHibernate will allow you to map directly to a private field which is very useful. Hopefully the EF team will understand the benefits gained from mapping to private fields.

Agreed, we want to enable mapping to properties (and get/set methods, etc.) in the future. Feel free to add another vote to the feature – https://entityframework.codeplex.com/workitem/93.


Where's The Comment Form?

    About

    Rowan works as a Program Manager for the ADO.NET Entity Framework team at Microsoft. He speaks at technical conferences and blogs at romiller.com. Rowan lives in Seattle, Washington with his wife Athalie. Prior to moving to the US he resided in the small state of Tasmania in Australia. Outside of technology Rowan's passions include snowboarding, mountain biking, horse riding, rock climbing and pretty much anything else that involves being active. The primary focus of his life, however, is to follow Jesus.

    RSS

    Subscribe Via RSS

    • Subscribe with Bloglines
    • Add your feed to Newsburst from CNET News.com
    • Subscribe in Google Reader
    • Add to My Yahoo!
    • Subscribe in NewsGator Online
    • The latest comments to all posts in RSS

    Meta

Liked it here?
Why not try sites on the blogroll...

Follow

Get every new post delivered to your Inbox.

Join 146 other followers

%d bloggers like this: