entity framework execute SQL before migrations

后端 未结 1 1981
不知归路
不知归路 2021-01-04 01:33

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 DbMigrationsConf

相关标签:
1条回答
  • 2021-01-04 02:30

    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
    0 讨论(0)
提交回复
热议问题