Automatically Adding Entity Framework Config Classes to the ModelBuilder

I should start off by saying this isn’t my code, I copied it from somewhere, but I cannot remember where. So, if you know send me a comment and I’ll update this post accordingly.

One of my pet peeves with entity framework code first, is having to add all my config classes to the modelBuilder within my context, like so….

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new UserConfig());
        modelBuilder.Configurations.Add(new TitleConfig());
        modelBuilder.Configurations.Add(new UserTitleConfig());
    }
}

But that’s a real PITA. I don’t want to have to remember to add every config class in that method every time I extend my model. It also starts to become untidy very quickly.

namespace MyProject
{
    public class MyContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            Assembly.GetExecutingAssembly().GetTypes()
                .Where(type => type.Namespace == "MyProject.Config")
                .ToList()
                .ForEach(type =>
                {
                    dynamic instance = Activator.CreateInstance(type);
                    modelBuilder.Configurations.Add(instance);
                });
        }
    }
}

That’s better! Now I can forget about that minor detail and get on with creating my model. I’ve used the namespace of the type to limit the scope to just my “config” folder. You may want to do it some other way or even choose not to limit it in any way.

EDIT (13 Dec 2011)

I have since found a better way of filtering the types to load …

    .Where(type => type.BaseType != null &&
        type.BaseType.IsGenericType &&
        type.BaseType.GetGenericTypeDefinition() == typeof (EntityTypeConfiguration<>))
Advertisements

One response to “Automatically Adding Entity Framework Config Classes to the ModelBuilder

  1. Pingback: antony_scott » Blog Archive » Automatically Adding Entity Framework Config Classes to the Model Builder (Version 2)

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