c# - 更改列的 IDENTITY 属性,需要删除并重新创建该列

标签 c# asp.net entity-framework entity-framework-core ef-core-2.1

我正在使用 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; }

}

但我意识到 IdCustomerId 两者都是开销,因为它们是一对一的关系,我可以按如下方式更新我的 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: To change the IDENTITY property of a column, the column needs to be dropped and recreated.

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

最佳答案

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

第一步

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

第 2 步

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

关于c# - 更改列的 IDENTITY 属性,需要删除并重新创建该列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53408175/

相关文章:

c# - 如何在 C# .Net 中使用 InsertOneAsync 将文档插入到 MongoDB 并返回相同的文档或其 ID

.net - System.Data.Entity.ModelConfiguration.Mappers.TypeMapper 在哪个程序集中定义?

c# - MembershipUser 和 Entity Framework 代码优先

c# - 对象必须实现 iconvertible devexpress

c# - 如何解决 'Windows Azure' 转换 ASP.NET 3.5 到 4.0 的此错误?

ASP.NET 错误 : More than one DbContext was found. 指定要使用哪一个

asp.net - 为什么创建 ASPNETDB.mdf 以及如何摆脱它?

c# - 无法连接到 PayPal 沙盒以验证 IPN 监听器收到的消息

c# - 错误 WebHostBuilder 只允许创建 WebHost 的单个实例

c# - 根据值限制 IObservable