要
public class City
{
...
public virtual ICollection<Student> BirthCityStudents { get; set; }
public virtual ICollection<Student> LivingCityStudents { get; set; }
}
然後,Student
實現你想要的東西,你需要提供一些輔助配置。代碼第一個約定可以識別雙向關係,但不是當存在多個時,多個 多您可以添加配置(使用數據註釋或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; }
}
這樣你明確指定要涉及與Students
導航屬性的BirthCity
導航屬性的關係的另一端。
使用流暢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);
}
隨着你不需要使用任何attibute這最後的解決方案。
現在,@ChristPratt的建議在您的City
類中爲每個關係都有一個Student
的集合,這真的很有用。如果你這樣做,然後使用數據註釋的配置可能是這樣的:使用流暢API遵循同樣的理念
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; }
}
或者:
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);
}
我簡化了我的清晰的代碼,但我的代碼與此完全相似。另一方面,我已經嘗試從頭開始重新創建數據庫2-3次,但現在我再次做同樣的事情,並在幾分鐘內通知您。 – 2015-02-17 21:45:00
@ChrisPratt:以下是我現在遵循的步驟:1)從我的項目中刪除遷移文件夾及其內容。 2)清理並重建解決方案中的所有項目。 3)在Package Manager控制檯上啓用遷移,然後添加AutomaticMigrationsEnabled = true;和AutomaticMigrationDataLossAllowed = true;到配置文件的構造函數。 4)添加遷移。 >>> – 2015-02-17 21:59:27
@ChrisPratt:但是在這一步之後,我再次觀察到在Up方法中有一個屬性「City_ID = c.Int()」。但是,我在解決方案中搜索並沒有「City_ID」屬性。那麼,爲什麼這個未定義的計劃被添加到項目中?提前致謝。 – 2015-02-17 22:01:20