如何在 EF 的同一个 class (table) 中添加两个外键
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);
}
```
我正在使用 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);
}
```