c# - Entity Framework 错误 : The ForeignKeyAttribute on property is not valid

标签 c# entity-framework entity-framework-6

我收到错误然后尝试将 AgendaType 添加到数据库上下文:

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 上指定了外键,就像在提供的数据库方案中一样。哪里不对?

最佳答案

编辑:在 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("FK_AgendaType")]
public int AgendaTypeId { get; set; }

关于c# - Entity Framework 错误 : The ForeignKeyAttribute on property is not valid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39743908/

相关文章:

c# - Entity Framework : How to set model as Serializable in Entity Framework

entity-framework - 如果数据库被删除,如何使用 CodeFirst 创建 LocalDB?

asp.net-mvc - 在 ASP.NET MVC 中使用 Entity Framework 是否允许我的 Web 项目在不同的数据库供应商上工作

c# - SQLite 连接未出现在实体数据模型向导中 (vs2015)

c# - C# MongoDB.Driver 2.0.0-beta1 中缺少 SetRepresentation() 方法

c# - vs2008/vs2010 在 TextBox 中是否有插入符位置更改事件?

c# - 以编程方式打开高级安全设置对话框?

c# - 已为应用付费的用户的应用内购买

.net - 带有 .Net 应用程序的 MySql 或 MS Sql Server

c# - 更改父属性并删除子项时 Entity Framework 引发异常