【发布时间】:2020-07-30 20:48:45
【问题描述】:
我正在尝试使用 EF 代码优先迁移向我的数据库表添加外键,但是当我运行 add-migration 时,生成的迁移中的 Up() 和 Down() 方法为空。
外键应该链接到的基表是Reservation,而我要添加键的表是Batch。
预留模型类:
public class Reservation
{
[Key]
public int ReservationId { get; set; }
public virtual ICollection<Batch> Batches { get; set; }
...
}
Batch模型类:
public class Batch
{
[Key]
public int BatchId { get; set; }
public int ReservationId { get; set; }
[ForeignKey("ReservationId")]
public Reservation Reservation { get; set; }
...
}
Reservation 属性以前称为 TempReservation,并且没有 [ForeignKey] 注释,这就是为什么一开始没有创建外键的原因。
我尝试通过添加[ForeignKey] 注释并将属性名称更改为Reservation 来修复它,就像上面的代码 sn-p 显示的那样,但无济于事。
迁移总是忽略我的更改,给我空Up() 和Down()。
我还有其他遵循相同“结构”的模型类,它们都有外键,没有任何问题。唯一的区别是我在 Batch 表已经创建之后添加这个 FK。
【问题讨论】:
-
您显示的代码并不表示有任何问题。
-
更新:我仍然无法让它生成应有的迁移,谁知道为什么,但我能够通过手动添加
AddForeignKey("dbo.Batches", "ReservationId", "dbo.Reservations", "ReservationId", cascadeDelete: true);到迁移来添加外键。
标签: c# entity-framework entity-framework-6 ef-code-first entity-framework-migrations