2016-09-28 55 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