我的 MVC 应用程序中有两个实体,我使用 Entity Framework 6 Code First 方法填充数据库。 Student实体中有两个city id;其中一个用于出生城市,另一个用于工作城市。当我按上面定义外键时,迁移后会在 Student 表中创建一个名为 City_ID 的额外列。是否有错误或者如何定义这些 FK?提前致谢。
学生:
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")]
public virtual City BirthCity { get; set; }
[ForeignKey("LivingCityID")]
public virtual City LivingCity { get; set; }
}
城市:
public class City
{
public int ID { get; set; }
public string CityName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
最佳答案
为了实现你想要的,你需要提供一些额外的配置。Code First约定可以识别双向关系,但当有
两个实体之间的多个双向关系。您可以添加配置(使用数据注释或Fluent API)来呈现此关系
向模型构建者提供信息。通过数据注释,您将使用注释
叫InverseProperty
。使用 Fluent API,您将使用 Has
/With
方法的组合来指定这些关系的正确端。
使用数据注释可能像这样:
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
导航属性相关联。
使用Fluent 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 对于每个关系的 City
类中的 Student
集合的建议非常有用。如果您这样做,那么使用数据注释的配置可能是这样的:
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; }
}
或者使用Fluent 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);
}
关于asp.net-mvc - 在 Entity Framework 代码优先中为同一个表定义多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28570916/