Countriesテーブルへの2つの外部キーを持つテーブルUserFormがありますが、(UserFormsモデルの)コントローラとビューの作成時に、外部キーにリンクしている2つのフィールドは表示されません。この問題を解決するにはどうすればいいですか。以下は2つのモデルです。
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?
置き換えint?
または代わりにSystem.Nullable<int>
(データベースにint NOT NULL
ではなく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; }
}