我正在用Entity Framework 6 Code First編寫ASP.NET MVC 5應用程序,並且遇到了一些外鍵問題。爲了舉例說明問題,我展示了兩個表格,國家和貨幣。實體框架外鍵屬性使用問題
的國家模型代表了國家和它們的屬性表:
[Table("dbo.Country")]
public class Country {
[Key]
[StringLength(2)]
[Display(Name = "L_Country_ISO2", ResourceType = typeof(ResxGlobal))]
public string iso { get; set; }
[Required]
[StringLength(80)]
[Display(Name = "L_Country", ResourceType = typeof(ResxGlobal))]
public string name { get; set; }
[Required]
[StringLength(80)]
public string nicename { get; set; }
[StringLength(3)]
[Display(Name = "L_Country_ISO3", ResourceType = typeof(ResxGlobal))]
public string iso3 { get; set; }
public short? numcode { get; set; }
[Display(Name = "L_DialCode", ResourceType = typeof(ResxGlobal))]
public int phonecode { get; set; }
}
而且我有一個單獨的表名爲貨幣,列出了其PK是兩個字母的ISO國家代碼這是該國的貨幣屬性在同一時間FK到國家表:
[Table("dbo.Currency")]
public class Currency {
[Key]
[StringLength(2)]
[Display(Name = "L_Country_ISO2", ResourceType = typeof(ResxGlobal))]
public string CountryCode { get; set; }
[Required, StringLength(100)]
[Display(Name="Currency name")]
public string CurrencyName { get; set; }
[Required, StringLength(3)]
[Display(Name="Currency code")]
public string CurrencyCode { get; set; }
[StringLength(5)]
public string Symbol { get; set; }
//[ForeignKey("CountryCode")]
public virtual Country Country {get; set; }
}
到目前爲止好所以現在看看第二個模型(貨幣)。如果我啓用指定CountryCode PK也是導航屬性Country使用的FK並執行遷移的ForeignKey屬性,則SQL Server圖表顯示國家和Currencya與PK(它們的小關鍵)終止符之間的關係關係的兩端,而通常情況下,小型鑰匙圖標顯示在PK表上,並且在關係的FK結束時顯示小無窮大圖標。我發現這很奇怪。
我恢復了遷移,刪除(註釋掉)了外鍵屬性並再次更新了數據庫。這一次的關係表現出我期望的PK與鑰匙和其他無窮大的圖標。但是,該表顯示了一個額外的列,我沒有在我的模型中指定。我手動編輯遷移以省略我的模型中未指定的名爲「Country_iso」的額外列。
在更新數據庫之前刪除(從遷移代碼)不需要的Country_iso列我發現當我嘗試使用數據庫上下文來檢索貨幣時,出現「Invalid column name Country_iso」錯誤。它在哪裏堅持要獲得我沒有的專欄?我沒有在任何地方看到這個引用,它隱藏在某個元數據文件的某處嗎?
那麼在模型中建立FK關係(一對一和一對多)的正確方法是什麼?