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?
First you need to create a migration. Then in the generated migration file you can write your SQL.
You can do this by running the Enable-Migrations command in Package Manager Console. This command will create a folder in your solution called Migrations, and put a single class inside it called Configuration.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With