根据惯例进行一对多映射
在最后一个示例中,你可以看到 EF 确定哪个列是外键,以及它应指向哪个列。怎么样?通过使用约定。具有 Person 类型的属性,其名称为 Person,具有 PersonId 属性,导致 EF 得出 PersonId 是外键的结论,并且它指向由 Person 类型表示的表的主键。
但是,如果你要改变 PERSONID 到 OWNERID 和人对业主的车类型?
public class Car
{
public int CarId { get; set; }
public string LicensePlate { get; set; }
public int OwnerId { get; set; }
public virtual Person Owner { get; set; }
}
好吧,不幸的是,在这种情况下,约定不足以生成正确的数据库模式: 
别担心; 你可以帮助 EF 提供有关你的关系和模型中的键的一些提示。只需配置 Car 类型即可将 OwnerId 属性用作 FK。创建实体类型配置并将其应用于 OnModelCreating():
public class CarEntityTypeConfiguration : EntityTypeConfiguration<Car>
{
public `CarEntityTypeConfiguration()`
{
this.HasRequired(c => c.Owner).WithMany(p => p.Cars).HasForeignKey(c => c.OwnerId);
}
}
这基本上说 Car 有一个必需的属性 Owner( HasRequired() ),在 Owner 的类型中,Cars 属性用于引用汽车实体( WithMany() )。最后指定了表示外键的属性( HasForeignKey() )。这为我们提供了我们想要的架构: 
你也可以从 Person 侧配置关系:
public class PersonEntityTypeConfiguration : EntityTypeConfiguration<Person>
{
public `PersonEntityTypeConfiguration()`
{
this.HasMany(p => p.Cars).WithRequired(c => c.Owner).HasForeignKey(c => c.OwnerId);
}
}
这个想法是一样的,只是两边是不同的(注意你如何阅读整个事情:‘这个人有很多车,每辆车都有一个必需的车主’)。如果你配置 Person 侧或 Car 侧的关系无关紧要。你甚至可以包括两者,但在这种情况下要注意在两边指定相同的关系!