Home > Coding > Executing Scripts during EF Code First Migrations

Executing Scripts during EF Code First Migrations

September 20th, 2012 Leave a comment Go to comments

I’ve spent the last two days converting a training application from Model First to Code first and enabling Migrations.  I knew I wanted to use the Migrations functionality on a new project that I’m starting in a few weeks and converting an existing application seemed the best way to really get my hands dirty.  I must say, I love the possibilities that this new feature set opens up, especially around just working within the development team.  No more “Oh, yea, I updated the database last night, I forgot to check in the script, I’ll send it right away”.  The development code will just update itself.  Glorious.

One issue I ran into is the ability to execute an arbitrary script as part of a migration.  I wanted to do this so that the initial configuration would also create the asp.net membership provider objects and the Sql Server ELMAH objects that are used behind the scenes.  One less thing to think about for a new developer or pushing into a new Dev/QA environment.

After much googling, it seemed that there is no good way to accomplish this task.  The migrations code exposes a Sql() command that will execute one sql statement, and you can do the same thing in the Configuration.Seed function by accessing the context directly.  Either way, not as clean as just giving an entire script over to Sql Server for execution.

I had a fully executable script, so instead of trying to parse it out manually as almost every post I found said to do, I worked around it by using this code:

I embedded the two scripts into my model assembly and then just split them apart to execute each statement one at a time.   I had to use “GO\r\n” due to the fact that the aspnet objects actually use GOTO in them.

It feels a little hackish, but it gets the job done and simplifies the initial creation as well as the maintenance of these objects.   This gets us back to, when a new developer starts.

Dev: “How do I set up the database”
Everyone: “Run the App”



Categories: Coding Tags: ,
  1. JGomez
    November 7th, 2012 at 22:40 | #1

    Hi, Thanks for your post!! How do you handle the scenario for pre-deployment/post-deployment scripts? Do you manually modify the migration file to add the script execution? pre-deployment/post-deployment are specific to every db version

  1. No trackbacks yet.