2016-09-28 72 views
1

我收到那麼錯誤嘗試AgendaType添加到數據庫方面:實體框架的錯誤:對財產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")]置於AgendaTypeId屬性中,如下所示:

[ForeignKey("FK_Agenda_AgendaType")] 
public int AgendaTypeId { get; set; } 

編輯:好像ForeignKey的名字應該是不同的:

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

現在我越來越: 附加信息:ForeignKeyAttribute財產「AgendaTypeId」上鍵入「MyDb.Agendum」是無效的。在依賴類型'MyDb.Agendum'上未找到導航屬性「FK_Agenda_AgendaType」。名稱值應該是有效的導航屬性名稱。 – amuliar

+0

感謝您關注我的問題,@Jakub!現在,我得到: '附加信息:類型'MyDb.Agendum'屬性'AgendaTypeId'上的ForeignKeyAttribute無效。在依賴類型'MyDb.Agendum'上找不到導航屬性'FK_AgendaType'。名稱值應該是一個有效的導航屬性名稱.' 然而,通過'[ForeignKey(「AgendaTypeId」)]'屬性AgendaType它的工作原理(默認名稱約定?),但我懷疑它會使用相同的FK。 – amuliar

相關問題