EF迁移脚本以退出条件的迁移

发布于 2025-02-08 13:01:24 字数 65 浏览 1 评论 0原文

我想在条件的基础上以代码第一次方法中的迁移。

假设,如果条件为真,我想在不更改数据库的情况下退出迁移。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月下凄凉 2025-02-15 13:01:25

migrationBuilder.sql(String,boolean)方法,因此创建一个SQL脚本,并使用您想使用(如果... else条件)进行操作。然后创建一个空迁移,然后在sql()方法中写下脚本,为 verbatim 字符串。

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.
}

如果您不知道如何为迁移创建脚本,请使用脚本移民

我认为您无法运行查询或对迁移的注入服务,因为实体 - 框架命令行工具分析了您的代码,但不运行startup.cs类。

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. Then create an empty migration and write the script in the Sql() method as a verbatim string.

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文