gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:22:41 27 4
gpt4 key购买 nike

我收到错误然后尝试将 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com