更改列的IDENTITY属性,需要删除该列并重新创建 [英] Change the IDENTITY property of a column, the column needs to be dropped and recreated

查看:949
本文介绍了更改列的IDENTITY属性,需要删除该列并重新创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 EF Core 2.1

这是我最初的模型定义。

This was my initial model definition.

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 & CustomerId 都是一对一的关系,因此,我可以如下更新我的BankAccount模型定义。

But I realized having Id & CustomerId both is overhead as its One-to-One relation, I can update my BankAccount model definition as below.

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类中定义了以下主体实体。

While in DbContext class defined the principal entity as below.

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

正在运行更新数据库得到以下错误。

While running the update-database I am getting the below error.


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

System.InvalidOperationException: To change the IDENTITY property of a column, the column needs to be dropped and recreated.

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

However, ideally I should not but just get rid of this error, I deleted the column, constraints and as well table and then the complete database as well. But still the same error.

推荐答案

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

I ran into the same problem, and I solved it by two steps and two migrations:

第1步


  1. 删除身份列。

  2. 注释BankAccount中的ID并添加一个新ID(即BankAccountId为

    身份,添加迁移和更新-这会删除ID)。

  3. 添加新列作为标识。

第2步


  1. 删除新添加的列,然后重新添加上一列。
    注释BankAccountId和取消注释ID。

  2. 添加迁移和更新(这将删除BankAccountId并添加ID作为标识)。

这篇关于更改列的IDENTITY属性,需要删除该列并重新创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆