In my last post I discussed how to inherit from the
EntityTypeConfiguration class and use reflection to dynamically configure Entity Framework. In this post I'll expand on that technique by using a custom interface, reflection, and several helper classes to automatically apply Entity Framework configurations from arbitrary classes.
One of the things I really like about Entity Framework Code First is the way you can mix declarative configuration (I.e., by using Data Annotation attributes) with programmatic configuration for more complicated cases (I.e., by using the fluent API). The one aspect of this that really bothers me though is that in normal usage the fluent API commands end up being placed inside your
DbContext class removed from your actual entity. If you change some aspect of an entity that uses the fluent API for configuration, you have to remember to go check the
OnModelCreating() method to ensure you don't need to modify the code-based configuration. It would be much better (in my opinion) if all configuration, declarative and programmatic, were located close to the entity and/or encapsulated within it. This article explains one way of accomplishing this.