16

I am working on an existing project that uses Entity-Framework 6 with code-first. I have a need to run some SQL before the migrations run.

I have a DbMigrationsConfiguration class with a seed method, but seed runs after the migrations.

I think it will work if I run my SQL in the constructor but I can't get a reference to the context.

Does anyone know how to do this?

Don Chambers
  • 3,798
  • 9
  • 33
  • 74

1 Answers1

26

You could use the 'Sql' method within the desired migration class.

public partial class OneOfYourMigrations : DbMigration 
{ 
    public override void Up() 
    { 
        //EF generated migration code here such as
        //CreateTable or AddColumn etc...
        //Now run your custom sql - here I'm doing an update to an existing column
        Sql("UPDATE dbo.YourTable SET Column1 = 'VALUE1' "); 
    } 

    public override void Down() 
    { 
        //EF generated code to rollback
    } 
}     

So the steps are;

  • Generate migration class using Add-Migration
  • Alter the class using code similar to above
  • Run the migration using Update-Database
Uchitha
  • 998
  • 8
  • 24
  • Can you explain more detail? I thought migrations run once and only once. This would work if it will run every time but it only seems to run one time. – Don Chambers Oct 27 '14 at 13:20
  • May be I could be more specific if I knew what kind of SQL you want to run? Is it modification of data (like I mentioned above) or is it something else? FYI, a given migration runs once against a given db, but you can always roll back a given migration - change it (i.e Add Sql) and run it again. – Uchitha Oct 27 '14 at 21:19
  • Want to run a script? http://stackoverflow.com/questions/32125937/can-we-run-sql-script-using-code-first-migrations – JackMorrissey Jun 03 '16 at 18:30