amuliar amuliar - 2 months ago 54
C# Question

Entity Framework error: The ForeignKeyAttribute on property is not valid

I receive error then trying to add AgendaType to database context:


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; }
}


However I specified foreign key on property AgendaType, as in provided database scheme. What is incorrect?

Answer

EDIT: After OP's comments, I dug up a little more. According to DataAnnotations explanation, [ForeignKey] can be indeed applied to the navigation property or the key property, but not both at the same time (examples in the provided link explain the usage). You should only use the attribute if the name of the foreign key is different than the convention. Do note, that when doing:

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

then the int foreign key property should be:

public int FK_Agenda_AgendaType { get;set; }

Older parts of the post, kept here to document the history of discussion:

You have to put the [ForeignKey("FK_Agenda_AgendaType")] on the AgendaTypeId property, like this:

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

EDIT: Seems like the ForeignKey name should be different:

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