【问题标题】:ASP EF7 Set column value in migrationASP EF7 在迁移中设置列值
【发布时间】:2016-06-07 02:50:39
【问题描述】:

我想从自动增量 ID 转移到复合主键。所以,这两个实体

public class SeasonTeam
{
    public int SeasonTeamId { get; set; }
    public int SeasonId { get; set; }   
    public int TeamId { get; set; }
}


public class GroupEntry
{
    public int GroupEntryId { get; set; }
    public int SeasonTeamId { get; set; }

    public SeasonTeam SeasonTeam { get; set; }
}

现在看起来像这样

public class SeasonTeam
{
    public int SeasonId { get; set; }   
    public int TeamId { get; set; }
}


public class GroupEntry
{
    public int GroupEntryId { get; set; }
    public int SeasonId { get; set; }   
    public int TeamId { get; set; }

    public SeasonTeam SeasonTeam { get; set; }
}

Visual Studio 生成迁移代码,但它损坏了数据。

migrationBuilder.AddColumn<int>(
    name: "SeasonId",
    table: "GroupEntry",
    nullable: false,
    defaultValue: 0);

migrationBuilder.AddColumn<int>(
    name: "TeamId",
    table: "GroupEntry",
    nullable: false,
    defaultValue: 0);



migrationBuilder.DropForeignKey(name: "FK_GroupEntry_SeasonTeam_SeasonTeamId", table: "GroupEntry");
migrationBuilder.DropPrimaryKey(name: "PK_SeasonTeam", table: "SeasonTeam");
migrationBuilder.DropColumn(name: "SeasonTeamId", table: "SeasonTeam");

默认值 0 显然不起作用,我需要引用的 SeasonTeam 表中的 id,但我没有找到任何示例。在删除旧的主键列之前,如何为新的复合键设置正确的 id 值?

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc entity-framework-core entity-framework-migrations


    【解决方案1】:

    您无法使用 EF 的 API 以编程方式执行此操作,但是,如果您可以编写 SQL 以将值从一个表移动到另一个表,则可以在添加列操作之后和删除列操作之前添加自定义迁移步骤.

    migrationBuilder.Sql(@"INSERT INTO ...(your SQL here)");
    

    根据您问题中的有限信息,我无法告诉您该 SQL 应该是什么。

    【讨论】:

    • 这似乎是一种方法。你知道 AddColumn 调用中参数 defaultValueSql 的目的是什么吗?
    • 示例:CREATE TABLE t (Modified DateTime2 DEFAULT GETDATE()). 您将设置 defaultValueSql = "GETDATE()"。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多