c# - 更改列的 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
& CustomerId
both 是一对一关系的开销,我可以更新我的 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 属性,需要删除并重新创建该列。
但是,理想情况下,我不应该只是摆脱这个错误,我删除了列、约束和表,然后也删除了完整的数据库。但仍然是同样的错误。
解决方案
我遇到了同样的问题,我通过两个步骤和两个迁移解决了它:
步骤1
- 删除标识列。
- 注释 BankAccount 中的 ID 并添加一个新的(即 BankAccountId 作为
身份,添加迁移和更新 - 这会删除 id)。 - 添加一个新列作为标识。
第2步
- 删除新添加的列并重新添加前一列。评论 BankAccountId 和取消评论 ID。
- 添加迁移和更新(这会删除 BankAccountId 并将 Id 添加为身份)。
推荐阅读
- python - 线程完成的进程永远不会退出
- java - Docker Build 命令在 Windows 10 上失败。使用的 Docker 版本是 19.03.5
- javascript - 如何将javascript文件添加到自定义表单并将数据传递给js文件
- php - 从 PHP 5.6 升级到 7.4
- c - 使用 VK_PRESENT_MODE_FIFO_KHR 时的 Vulkan 重影
- swift - 如何在 RealityKit 中访问 Reality Composer 的模型组件?
- javascript - 对象属性在更新时会覆盖所有网格
- c# - 将 Crystal Report 与数据集连接起来
- java - 如何使用 POI 删除表格后的第一个字符
- c# - 如何在 .NET Standard 2.0/Core 2.1 中使用 PrivateKey 创建 X509Certificate2?