entity framework execute SQL before migrations

ef-code-first entity-framework-6

Question

I'm working on an ongoing project that employs code-first and Entity-Framework 6. I must do some SQL queries prior to the migrations starting.

Despite having a seed method in my DbMigrationsConfiguration class, seed only executes after the migrations.

Even though I can't get a reference to the context, I believe it will work if I run my SQL in the constructor.

Anyone who is capable of doing this?

1
15
10/23/2014 6:48:08 PM

Popular Answer

The 'Sql' method is available within the chosen 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;

  • Use Add-Migration to create a migration class.
  • Modify the class using the aforementioned code.
  • Use Update-Database to carry out the migration.
21
10/25/2014 10:34:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow