首页 > 解决方案 > 更改列的 IDENTITY 属性,需要删除并重新创建列

问题描述

我正在使用EF Core 2.1

这是我最初的模型定义。

public class Customer //Parent
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public BankAccount BankAccount { get; set; }

}


public class BankAccount
{
    public int Id { get; set; }

    public string Branch { get; set; }

    public string AcntNumber { get; set; }

    public DateTime CreatedDate { get; set; }

    public int CustomerId { get; set; }

    public Customer Customer { get; set; }

}

但是我意识到拥有Id& CustomerIdboth 是一对一关系的开销,我可以更新我的 BankAccount 模型定义,如下所示。

public class BankAccount
{
    public int Id { get; set; }

    public string Branch { get; set; }

    public string AcntNumber { get; set; }

    public DateTime CreatedDate { get; set; }

    public Customer Customer { get; set; }

}

而在 DbContext 类中定义主体实体如下。

HasOne(b => b.Customer).WithOne(c => c.BankAccount).HasForeignKey<BankAccount>(f => f.Id);

运行update-database时出现以下错误。

System.InvalidOperationException:要更改列的 IDENTITY 属性,需要删除并重新创建该列。

但是,理想情况下,我不应该只是摆脱这个错误,我删除了列、约束和表,然后也删除了完整的数据库。但仍然是同样的错误。

标签: c#asp.netentity-frameworkentity-framework-coreef-core-2.1

解决方案


我遇到了同样的问题,我通过两个步骤和两个迁移解决了它:

步骤1

  1. 删除标识列。
  2. 注释 BankAccount 中的 ID 并添加一个新的(即 BankAccountId 作为
    身份,添加迁移和更新 - 这会删除 id)。
  3. 添加一个新列作为标识。

第2步

  1. 删除新添加的列并重新添加前一列。评论 BankAccountId 和取消评论 ID。
  2. 添加迁移和更新(这会删除 BankAccountId 并将 Id 添加为身份)。

推荐阅读