【问题标题】:Conditionally inserting data in a code-first migration with Entity Framework使用实体框架在代码优先迁移中有条件地插入数据
【发布时间】:2020-01-20 12:19:34
【问题描述】:

我正在尝试使用实体框架进行第二次迁移,到目前为止我生成了这样的代码

namespace Entity.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class LedgerDisplayOrder : DbMigration
    {
        public override void Up()
        {
            AddColumn("Ledgers", "DisplayOrder", c => c.Int());
            // Hic sunt leones
        }

        public override void Down()
        {
            DropColumn("Ledgers", "DisplayOrder");
        }
    }
}

如何填充这一列的逻辑其实很简单,在 SQL 中应该是这样的:

ALTER TABLE [Ledgers] ADD [DisplayOrder] INT NULL;

UPDATE [Ledgers] 
SET DisplayOrder = 10 
WHERE [Id] = 26 OR [Id] = 27 OR [Id] = 23; 

UPDATE [Ledgers] 
SET DisplayOrder = 20 
WHERE [Id] = 29 OR [Id] = 9; 

UPDATE [Ledgers] 
SET DisplayOrder = 30 
WHERE [Id] = 28 OR [Id] = 23; 

换句话说,迁移应该在迁移过程中自动填充,但我不确定在// hic sunt leones 放置什么来实现这一点。我读到我应该使用migrationBuilder class,可能类似于

migrationBuilder.InsertData(table: "ledger", column: "DisplayOrder", value: "10");

但是如何实现WHERE 子句呢?以及如何加载该类?我的 Visual Studio 的 Quick Actions and Refactoring 一直建议实现一个新类,所以我必须先安装一些东西吗?

感谢任何帮助!

参考:到目前为止,我发现的只是为新列设置默认值。这不是我所追求的。

【问题讨论】:

    标签: c# asp.net entity-framework entity-framework-migrations code-first


    【解决方案1】:

    您可以在迁移期间使用migrationBuilder.Sql 命令执行纯 SQL 表达式:

    你可以使用 InsertData 而不是

    Sql("UPDATE [Ledgers] 
         SET DisplayOrder = 10 
         WHERE [Id] = 26 OR [Id] = 27 OR [Id] = 23; ");
    

    这是migrationBuilder.Sql的缩写,可以通过

    加载
    using Microsoft.EntityFrameworkCore.Migrations;
    

    如果您使用的是 EF Core 或(在您的情况下)

    using System.Data.Entity.Migrations;
    

    如果您使用的是 EntityFramework。

    【讨论】:

    • 如果您使用的是 EF Core,则应将 using Microsoft.EntityFrameworkCore.Migrations; 添加到您的标题中,如果您使用的是 EF,则应添加 using System.Data.Entity.Migrations;
    • 是的,我的例子来自 EFCore 项目,其中migrationBuilderUp()/Down() 函数中作为参数出现。请原谅我的不准确。
    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    相关资源
    最近更新 更多