实体框架 - 如何使用“GO”创建sql脚本声明 [英] Entity Framework - how to create sql script with "GO" statements

查看:185
本文介绍了实体框架 - 如何使用“GO”创建sql脚本声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在EF 6.1中,您可以运行命令:

In EF 6.1 you can run the command:

update-database -script

这将生成一个或多个迁移的完整SQL脚本。我们发现的问题是它不会为sql server生成必需的GO语句。这将导致SQL脚本失败,否则如果直接运行而不使用-script参数,则会失败。

This generates the full SQL script for one or many migrations. The problem we found is that it does not generate the required "GO" statements for sql server. This is causing the SQL script to fail when it would otherwise succeed if run directly without the "-script" parameter.

有没有人遇到这种情况?

Has anyone else run into this?

推荐答案

您可以通过在SqlServerMigrationSqlGenerator类周围创建一个包装类来覆盖脚本生成行为。此类包含一个重载的Generate()方法,该方法接受代表其生成的脚本块类型的参数。您可以在启动新的脚本块之前重写这些方法来添加GO语句。

You can override the script generation behavior by creating a wrapper class around the SqlServerMigrationSqlGenerator class. This class contains an overloaded Generate() method which takes in arguments that represent the type of script block it's generating. You can override these methods to add "GO" statements before starting new script blocks.

public class ProdMigrationScriptBuilder : SqlServerMigrationSqlGenerator
{
    protected override void Generate(HistoryOperation insertHistoryOperation)
    {
        Statement("GO");
        base.Generate(insertHistoryOperation);
        Statement("GO");
    }

    protected override void Generate(CreateProcedureOperation createProcedureOperation)
    {
        Statement("GO");
        base.Generate(createProcedureOperation);
    }

    protected override void Generate(AlterProcedureOperation alterProcedureOperation)
    {
        Statement("GO");
        base.Generate(alterProcedureOperation);
    }

    protected override void Generate(SqlOperation sqlOperation)
    {
        Statement("GO");
        base.Generate(sqlOperation);
    }
}

您还需要将此类设置为Sql您的配置类构造函数中的生成器。

You will also need to set this class as the Sql Generator in your Configuration class constructor.

    public Configuration()
    {
        AutomaticMigrationsEnabled = false;

       // Add back this line when creating script files for production migration...
       SetSqlGenerator("System.Data.SqlClient", new ProdMigrationScriptBuilder());

    }

这种方法的一个理由是,为SQL Server企业管理器创建可重用的脚本文件,GO语句在本地执行迁移时不起作用。您可以在本地工作时注释掉SetSqlGenerator行,然后在准备好创建部署脚本时简单地将其添加回来。

One gotcha to this approach is that while it works great for creating re-usable script files for SQL Server Enterprise Manager, the GO statements do not work when executing migrations locally. You can comment out the SetSqlGenerator line when working locally, then simply add it back when you are ready to create your deployment scripts.

这篇关于实体框架 - 如何使用“GO”创建sql脚本声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆