Adding 'GO' statements to Entity Framework migrations

前端 未结 5 1253
青春惊慌失措
青春惊慌失措 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:13

    Turn out the concept exist deep in the SqlServerMigrationSqlGenerator as an optional argument for Statement(sql, batchTerminator). Here is something based on Skyp idea. It works both in -script mode or not. The GOs are for different operations than for Skyp only because our needs are a little different. You then need to register this class in the Configuration as per Skyp instructions.

        public class MigrationScriptBuilder : SqlServerMigrationSqlGenerator
        {
            private string Marker = Guid.NewGuid().ToString(); //To cheat on the check null or empty of the base generator
    
            protected override void Generate(AlterProcedureOperation alterProcedureOperation)
            {
                SqlGo();
                base.Generate(alterProcedureOperation);
                SqlGo();
            }
            protected override void Generate(CreateProcedureOperation createProcedureOperation)
            {
                SqlGo();
                base.Generate(createProcedureOperation);
                SqlGo();
            }
            protected override void Generate(SqlOperation sqlOperation)
            {
                SqlGo();
                base.Generate(sqlOperation);
            }
    
            private void SqlGo()
            {
                Statement(Marker, batchTerminator: "GO");
            }
    
            public override IEnumerable Generate(IEnumerable migrationOperations, string providerManifestToken)
            {
                var result = new List();
                var statements = base.Generate(migrationOperations, providerManifestToken);
    
                bool pendingBatchTerminator = false;
                foreach (var item in statements)
                {
                    if(item.Sql == Marker && item.BatchTerminator == "GO")
                    {
                        pendingBatchTerminator = true;
                    }
                    else
                    {
                        if(pendingBatchTerminator)
                        {
                            item.BatchTerminator = "GO";
                            pendingBatchTerminator = false;
                        }
                        result.Add(item);
                    }
                }
    
                return result;
            }
        }
    

提交回复
热议问题