[英]How to add two foreign keys in the same class (table) in EF
我正在使用 EF 項目,我嘗試添加兩個外鍵,但是在添加遷移時遇到了問題。
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public DateTime? DeathDate { get; set; }
public int? FatherId { get; set; }
public int? MotherId { get; set; }
[ForeignKey("FatherId")]
public virtual Person Father { get; set; }
[ForeignKey("MotherId")]
public virtual Person Mother { get; set; }
}
在您的上下文中添加此代碼
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasOptional(a => a.Mother)
.WithMany()
.HasForeignKey(a => a.MotherId);
modelBuilder.Entity<Person>()
.HasOptional(a => a.Father)
.WithMany()
.HasForeignKey(a => a.FatherId);
}
```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.