更改列的 IDENTITY 属性,需要删除并重新创建该列 [英] Change the IDENTITY property of a column, the column needs to be dropped and recreated
问题描述
我使用的是 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);
在运行 update-database
时,我收到以下错误.
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:
第一步
- 删除标识列.
- 注释 BankAccount 中的 ID 并添加一个新 ID(即 BankAccountId as
身份,添加迁移和更新 - 这会删除 id). - 添加一个新列作为标识.
第 2 步
- 删除新添加的列并重新添加上一列.评论 BankAccountId 和取消评论 ID.
- 添加迁移和更新(这会删除 BankAccountId 并添加 Id 作为身份).
这篇关于更改列的 IDENTITY 属性,需要删除并重新创建该列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!