Adding 'GO' statements to Entity Framework migrations

前端 未结 5 1254
青春惊慌失措
青春惊慌失措 2020-12-01 16:36

So I have an application with a ton of migrations made by Entity framework. We want to get a script for all the migrations at once and using the -Script tag doe

5条回答
  •  醉梦人生
    2020-12-01 17:14

    In order to change the SQL Generated by entity framework migrations you can create a new SqlServerMigrationSqlGenerator

    We have done this to add a GO statement before and after the migration history:

    public  class MigrationScriptBuilder: SqlServerMigrationSqlGenerator
    {
        protected override void Generate(System.Data.Entity.Migrations.Model.InsertHistoryOperation insertHistoryOperation)
        {
            Statement("GO");
    
            base.Generate(insertHistoryOperation);
    
            Statement("GO");
    
        }
    }
    

    then add in the Configuration constructor (in the Migrations folder of the project where you DbContext is) so that it uses this new sql generator:

    [...]
    internal sealed class Configuration : DbMigrationsConfiguration
    {
        public Configuration()
        {
            SetSqlGenerator("System.Data.SqlClient", new MigrationScriptBuilder());
            AutomaticMigrationsEnabled = false;
        }
    [...]
    

    So now when you generate a script using the -Script tag, you can see that the insert into [__MigrationHistory] is surrounded by GO

    Alternatively in your implementation of SqlServerMigrationSqlGenerator you can override any part of the script generation, the InsertHistoryOperation was suitable for us.

提交回复
热议问题