我有一個表UserForms,它有一個States表的兩個外鍵,但在創建我的控制器和創建視圖(對於UserForms模型)時,不會出現鏈接到外鍵的兩個字段。我應該怎麼做才能解決這個問題?以下是兩種型號:
public class UserForms
{
public int Id { get; set; }
public string FullNames { get; set; }
public Countries IndividualsCountry { get; set; }
public Countries BusinessCountry { get; set; }
}
public class Countries
{
public Countries()
{
this.STRBusinessCountry = new HashSet<UserForms>();
this.STRIndividualsCountry = new HashSet<UserForms>();
}
public int Id { get; set; }
public string NameOfCountry { get; set; }
[InverseProperty("IndividualsCountry")]
public virtual ICollection<UserForm> STRIndividualsCountry { get; set; }
[InverseProperty("BusinessCountry")]
public virtual ICollection<UserForm> STRBusinessCountry { get; set; }
}
@ T.Glatzer留下的評論是正確的。您應該在依賴實體上公開外鍵屬性:
public class UserForms
{
public int Id { get; set; }
public string FullNames { get; set; }
public int IndividualsCountryId { get; set; }
[ForeignKey("IndividualsCountryId")]
public virtual Countries IndividualsCountry { get; set; }
public int BusinessCountryId { get; set; }
[ForeignKey("BusinessCountryId")]
public virtual Countries BusinessCountry { get; set; }
}
這裡我使用了int
,但如果這些導航屬性中的任何一個是可選的,你只需要替換int?
或者System.Nullable<int>
(它將在數據庫中創建一個int NULL
列而不是int NOT NULL
)。
雖然EF不要求您公開導航屬性,但通常是一個好習慣。相信我。它將幫助您以後避免意外的異常。事實上,一些EF異常消息實際上建議在實體類上公開外鍵屬性,以幫助EF更好地弄清楚如何映射關係。以下是一個此類例外的示例。注意“附加信息”部分:
{“INSERT語句與FOREIGN KEY約束衝突”FK_dbo.DependentTable_dbo.PrincipalTable_Id“。衝突發生在數據庫”DatabaseName“,表”dbo.PrincipalTable“,列'Id'。語句已被終止。”}
附加信息:保存不公開其關係的外鍵屬性的實體時發生錯誤。 EntityEntries屬性將返回null,因為無法將單個實體標識為異常的來源。通過在實體類型中公開外鍵屬性,可以更輕鬆地在保存時處理異常。有關詳細信息,請參閱InnerException。
@danludwig感謝你解釋@ T.Glatzer回答這對我有用!謝謝。我現在正在使用的最終代碼是
public class UserForms
{
public int Id { get; set; }
public string FullNames { get; set; }
[ForeignKey("IndividualsCountry")]
public int? IndividualsCountryId { get; set; }
[ForeignKey("BusinessCountry")]
public int? BusinessCountryId { get; set; }
public virtual Countries IndividualsCountry { get; set; }
public virtual Countries BusinessCountry { get; set; }
}
public class Countries
{
public Countries()
{
this.STRBusinessCountry = new HashSet<UserForms>();
this.STRIndividualsCountry = new HashSet<UserForms>();
}
public int Id { get; set; }
public string NameOfCountry { get; set; }
[InverseProperty("IndividualsCountry")]
public virtual ICollection<UserForms> STRIndividualsCountry { get; set; }
[InverseProperty("BusinessCountry")]
public virtual ICollection<UserForms> STRBusinessCountry { get; set; }
}