Code First Migrations – Customizing Scaffolded Code

Posted on November 30, 2012. Filed under: Entity Framework, Visual Studio | Tags: , , , , |

A while back I blogged about customizing the SQL that is generated by Code First Migrations. In this post I’m going to step back up the pipeline a bit and look at customizing the code that gets scaffolded when you call Add-Migration.

When we built Code First Migrations we made an effort to make everything pluggable. For example, the component that scaffolds the code of a migration based on the changes detected in your model should be replaceable with your own implementation.

We also tried to factor our implementations in such a way that it was easy to override small parts of the default behavior without writing a lot of code. For example, if you want to add a small section to the start of each migration that is scaffolded, you shouldn’t have to implement a complete code generator.

Creating a Custom Code Generator

Let’s say we want to add a couple of comments to the top of each migration that records who generated the migration and when they generated it. We can derive from the default code generator and override the method that generates the start of the class. In this example I’m writing the desired information to the IndentedTextWriter and then calling the base implementation to write the remainder of the default code.

using System;
using System.Data.Entity.Migrations.Design;
using System.Data.Entity.Migrations.Utilities;

public class MyCodeGenerator : CSharpMigrationCodeGenerator
    protected override void WriteClassStart(
        string @namespace,
        string className,
        IndentedTextWriter writer,
        string @base,
        bool designer = false,
        System.Collections.Generic.IEnumerable namespaces = null)
        writer.WriteLine("// Generated Time: {0}", DateTime.Now);
        writer.WriteLine("// Generated By: {0}", Environment.UserName);

        base.WriteClassStart(@namespace, className, writer, @base, designer, namespaces);

The easiest way to see what methods you can override, and what they do, is to look at the source code for the default implementation. That’s very easy because EF is open source and you can browse the source online. Under src\EntityFramework\Migrations\Design you’ll find CSharpMigrationCodeGenerator.cs and VisualBasicMigrationCodeGenerator.cs.

Registering a Custom Code Generator

Now that we’ve built a custom code generator we can register it in the constructor of our migration configuration class.

public Configuration()
    AutomaticMigrationsEnabled = false;
    CodeGenerator = new MyCodeGenerator();

Now if we run the Add-Migration command we’ll see the information is added to the top of the scaffolded code.

// Generated Time: 11/30/2012 2:35:08 PM
// Generated By: rowmil

namespace ConsoleApplication1.Migrations
    using System;
    using System.Data.Entity.Migrations;

    public partial class AddRating : DbMigration
        public override void Up()
            AddColumn("dbo.Blogs", "Rating", c => c.Int(nullable: false));

        public override void Down()
            DropColumn("dbo.Blogs", "Rating");

Make a Comment

Leave a Reply

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

You are commenting using your 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

3 Responses to “Code First Migrations – Customizing Scaffolded Code”

RSS Feed for Comments RSS Feed

[…] There were a number of good posts about Code First Migrations . Doug Rathbone blogged about using Code First Migrations in team environments. This one’s a bit older, but we wanted to point out a good post by Jarod Ferguson with some good tips for using Code First Migrations. Rowan Miller blogged about customizing the code that is scaffolded by Code First Migrations. […]

Don’t forget Eddie, the kids of troroomw will be addicted to some new technology, whatever it may be. And us old curmudgeons will yell at our kids for spending all their time with it, “We never had that kinda thing in MY day. We used the internet like a normal citizen”Hard to predict what it will be, I bet nobody in the ’80s could imagine how the internet would take off. It’s probably something right under our noses. Maybe Cell Phones will replace computers all together!

Hi Rowan,

How can we customize the file name it generates for the migration. Default is some timestamp with migration name. It would be nice to have in some scenarios where want to store these files in source control and have more meaningful names.


Where's The Comment Form?


    Rowan works as a Program Manager for the ADO.NET Entity Framework team at Microsoft. He speaks at technical conferences and blogs at 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.


    Subscribe Via RSS

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


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

%d bloggers like this: