为了实现你想要的,你需要提供一些额外的配置。Code First约定可以识别双向关系,但当有
两个实体之间的多个双向关系。您可以添加配置(使用数据注释 or the 流畅的API)来呈现这个
向模型构建者提供信息。通过数据注释,您将使用注释
被称为InverseProperty http://www.entityframeworktutorial.net/code-first/inverseproperty-dataannotations-attribute-in-code-first.aspx。通过 Fluent API,您将结合使用Has
/With
方法来指定这些关系的正确末端。
Using 数据注释可能是这样的:
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int BirthCityID { get; set; }
public int LivingCityID { get; set; }
[ForeignKey("BirthCityID")]
[InverseProperty("Students")]
public virtual City BirthCity { get; set; }
[ForeignKey("LivingCityID")]
public virtual City LivingCity { get; set; }
}
通过这种方式,您可以明确指定您想要关联BirthCity
导航属性与Students
关系另一端的导航属性。
Using 流畅的API可能是这样的:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasRequired(m => m.BirthCity)
.WithMany(m => m.Students).HasForeignKey(m=>m.BirthCityId);
modelBuilder.Entity<Student>().HasRequired(m => m.LivingCity)
.WithMany().HasForeignKey(m=>m.LivingCityId);
}
使用最后一个解决方案,您不需要使用属性。
现在,@ChristPratt 的建议是收集Student
在你的City
每个关系的类都非常有用。如果您这样做,则使用的配置数据注释可以是这样的:
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int BirthCityID { get; set; }
public int LivingCityID { get; set; }
[ForeignKey("BirthCityID")]
[InverseProperty("BirthCityStudents")]
public virtual City BirthCity { get; set; }
[ForeignKey("LivingCityID")]
[InverseProperty("LivingCityStudents")]
public virtual City LivingCity { get; set; }
}
或者使用流畅的API遵循同样的想法:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasRequired(m => m.BirthCity)
.WithMany(m => m.BirthCityStudents).HasForeignKey(m=>m.BirthCityId);
modelBuilder.Entity<Student>().HasRequired(m => m.LivingCity)
.WithMany(m => m.LivingCityStudents).HasForeignKey(m=>m.LivingCityId);
}