2016-09-28 3 views
1

ではありません、私は、データベースコンテキストにAgendaTypeを追加しようとエラーが表示されます。Entity Frameworkのエラー:プロパティのForeignKeyAttributeが有効

An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll Additional information: The ForeignKeyAttribute on property 'AgendaType' on type 'MyDb.Agendum' is not valid. The foreign key name 'FK_Agenda_AgendaType' was not found on the dependent type 'MyDb.Agendum'. The Name value should be a comma separated list of foreign key property names.

[Table("AgendaType")] 
public partial class AgendaType 
{ 
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] 
    public AgendaType() 
    { 
     Agenda = new HashSet<Agendum>(); 
    } 

    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 

    [Required] 
    [StringLength(2)] 
    [Index("IX_AgendaType_Code", 1, IsUnique = true)] 
    public string Code { get; set; } 

    [Required] 
    [StringLength(50)] 
    public string Name { get; set; } 

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] 
    public virtual ICollection<Agendum> Agenda { get; set; } 
} 

public partial class Agendum 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 

    public int AgendaTypeId { get; set; } 

    [ForeignKey("FK_Agenda_AgendaType")] 
    public virtual AgendaType AgendaType { get; set; } 
} 

私が提供するデータベース・スキームのように、プロパティAgendaTypeの外部キーを指定したが。何が間違っていますか?

答えて

1

編集:OPのコメントの後、もう少し掘り下げました。 DataAnnotations explanationによれば、実際にはナビゲーションプロパティまたはキープロパティに[ForeignKey]を適用できますが、両方同時に使用することはできません(提供されたリンクの例では使用方法が説明されています)。外部キーの名前が規約と異なる場合にのみ、属性を使用してください。やったときに、注意していることでください:

[ForeignKey("FK_Agenda_AgendaType")] 
public virtual AgendaType AgendaType { get; set; } 

を、その後int外部キープロパティは、次のようになります。

:ポストの

public int FK_Agenda_AgendaType { get;set; } 

古い部分は、議論の歴史を文書化するためにここに保管しました

[ForeignKey("FK_Agenda_AgendaType")] 
public int AgendaTypeId { get; set; } 
01のように[ForeignKey("FK_Agenda_AgendaType")]をAgendaTypeIdプロパティに配置する必要があります。

EDIT:ForeignKeyの名は異なっていなければなりませんように思える:

[ForeignKey("FK_AgendaType")] 
public int AgendaTypeId { get; set; } 
+0

今、私が取得: 追加情報:タイプのForeignKeyAttributeプロパティの「AgendaTypeIdは」「MyDb.Agendum」は有効ではありません。ナビゲーション・プロパティ 'FK_Agenda_AgendaType'は、依存タイプ 'MyDb.Agendum'に見つかりませんでした。 Name値は、有効なナビゲーションプロパティ名である必要があります。 – amuliar

+0

私の質問に気をつけてくれてありがとう、@ジャク!今すぐ取得しました: '追加情報:タイプ 'MyDb.Agendum'のプロパティ 'AgendaTypeId'のForeignKeyAttributeが無効です。ナビゲーションプロパティ 'FK_AgendaType'が依存型 'MyDb.Agendum'に見つかりませんでした。 'プロパティのAgendaType上で' [ForeignKey( "AgendaTypeId")] 'を実行すると(デフォルト名のコンベンションごとに)動作しますが、同じFKを使用するかどうかは疑問です。 – amuliar

関連する問題