简体   繁体   English

EF 迁移脚本在条件下退出迁移

[英]EF Migration script to exit migration on a condition

I want to abort the migration in code first approach on a condition basis.我想在条件的基础上中止代码优先方法的迁移。

Suppose, if the condition is true, I want to exit the migration without making changes to the database.假设,如果条件为真,我想退出迁移而不更改数据库。

This should be possible with MigrationBuilder.Sql(String, Boolean) method, so create an SQL script with what you want to do with IF...ELSE conditions.这应该可以通过MigrationBuilder.Sql(String, Boolean)方法实现,因此创建一个 SQL 脚本,其中包含您想要对IF...ELSE条件执行的操作。 Then create an empty migration and write the script in the Sql() method as a verbatim string.然后创建一个空迁移并将Sql()方法中的脚本编写为逐字字符串。

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql(@"
    BEGIN
        DECLARE @sales INT;

        SELECT 
            @sales = SUM(list_price * quantity)
        FROM
            sales.order_items i
            INNER JOIN sales.orders o ON o.order_id = i.order_id
        WHERE
            YEAR(order_date) = 2018;

        SELECT @sales;

        IF @sales > 1000000
        BEGIN
            -- // What you want to do if sales > 1,000,000
        END
    END
    ");
}

protected override void Down(MigrationBuilder migrationBuilder)
{
    // But you need to write another script to revert the changes done by Up method.
}

If you don't know how to create a script for your migration, use Script-Migration .如果您不知道如何为迁移创建脚本,请使用Script-Migration

I don't think you can run queries or inject services to migrations, since the Entity-framework command-line tool analyzes your code but does not run the startup.cs class.我认为您不能运行查询或向迁移注入服务,因为 Entity-framework 命令行工具会分析您的代码,但不会运行 startup.cs 类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM