對映零或一對多

在前面的例子中,沒有人就不能存在汽車。如果你想讓這個人在汽車方面是可選的怎麼辦?嗯,這很容易,知道如何做一對多。只需將 Car 中的 PersonId 更改為可為空即可:

public class Car
{
    public int CarId { get; set; }
    public string LicensePlate { get; set; }
    public int? PersonId { get; set; }
    public virtual Person Person { get; set; }
}

然後使用 HasOptional() (或 WithOptional() ,具體取決於你從哪 一方進行配置):

public class CarEntityTypeConfiguration : EntityTypeConfiguration<Car>
{
  public CarEntityTypeConfiguration()
  {
     this.HasOptional(c => c.Owner).WithMany(p => p.Cars).HasForeignKey(c => c.OwnerId);
  }
}