简体   繁体   English

使用实体框架在代码优先迁移中有条件地插入数据

[英]Conditionally inserting data in a code-first migration with Entity Framework

I am trying my 2nd migration using the Entity Framework, and so far I generated code like this我正在尝试使用实体框架进行第二次迁移,到目前为止我生成了这样的代码

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");
        }
    }
}

The logic how to fill this column is actually pretty simple, in SQL it would be something like the following:如何填充此列的逻辑实际上非常简单,在 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; 

In other words, the migration should automatically be populated during the migration, but I am not sure what to put at // hic sunt leones to achieve just that.换句话说,迁移过程中应该自动填充迁移,但我不确定在// hic sunt leones放什么来实现这一点。 I read that I should use the migrationBuilder class , probably something like我读到我应该使用migrationBuilder 类,可能类似于

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

but how to implement the WHERE clause?但是如何实现WHERE子句呢? And how do I load that class?我如何加载该类? My Visual Studio's Quick Actions and Refactoring keeps suggesting to implement a new class, so do I have to install something first?我的 Visual Studio 的快速操作和重构一直建议实现一个新类,所以我必须先安装一些东西吗?

Any help is appreciated!任何帮助表示赞赏!

References: all I found so far is about setting default values for a new column.参考资料:到目前为止,我发现的所有内容都是关于为新列设置默认值。 That's not what I am after.那不是我所追求的。

You can use migrationBuilder.Sql command to execute pure SQL-expressions during migration:您可以使用migrationBuilder.Sql命令在迁移期间执行纯 SQL 表达式:

Instead of InsertData you could use您可以使用而不是InsertData

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

This is short for migrationBuilder.Sql which can be loaded via这是migrationBuilder.Sql缩写,可以通过

using Microsoft.EntityFrameworkCore.Migrations;

if you are using EF Core or (in your case) by如果您正在使用 EF Core 或(在您的情况下)

using System.Data.Entity.Migrations;

if you are using EntityFramework.如果您使用的是 EntityFramework。

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

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