データアノテーションを使用して外部キーを作成します
-
20-12-2019 - |
質問
以下のコードでは、ParentQuestionAnswers.ID(主キーである)に依存するように、ParentInfoadDproperties.ParentQuestionAnswerSIDに外部キーの制約を設定する必要があります。データ注釈を使用して、エンティティフレームワーク6は、ParentInfoadDProperties.ID列Not ParentInfoadDProperties.ParentQuestionAnswerSidSwerSID列ではなく、ParentQuestionAnswers.ID列を参照している新しい外部キー列を作成したいと考えています。エンティティフレームワークが新しい外部キーコラムを作成したくない。
誰かがどのデータの注釈を説明するか(必要ならば)望ましい外部キーの制約を達成するために指定されるべきか(必要ならば)どのようなデータの注釈を説明することができれば大いに感謝します。事前にありがとうございます。
namespace Project.Domain.Entities
{
public class ParentQuestionAnswers
{
public ParentQuestionAnswers()
{
ParentInfoAddProperties = new ParentInfoAddProperties();
}
[Required]
public int Id { get; set; }
[Required]
public int UserId { get; set; }
public ParentInfoAddProperties ParentInfoAddProperties { get; set; }
}
public class ParentInfoAddProperties
{
[Required]
public int Id { get; set; }
[Required]
public int ParentQuestionAnswersId { get; set; }
}
}
. 解決
次のデータ注釈を使用し、int
の代わりにエンティティを使用できます。[Required]
[ForeignKey("ParentQuestionAnswers")]
public ParentQuestionAnswers ParentQuestionAnswers { get; set; }
.
IDを取得するには、プロパティ
を追加することができます。public int ParentQuestionAnswersId { get; set; }
.
しかし、あなたはまだParentQuestionAnswers
プロパティを必要とするので、EFはあなたを理解するでしょう。
(これらのコード行はParentInfoAddProperties
クラスの下にあるはずです)
他のヒント
を追加します
[KeyAttribute]
.
ID列
と
[ForeignKeyAttribute]
.
ParentQuestionAnswerSIDプロパティ。