Home > Mobile >  How do I add multiple self-referencing foreign keys to my EF class?
How do I add multiple self-referencing foreign keys to my EF class?

Time:08-26

public class ConceptData {
    [Key]
    public long Id { get; set; }

    public string Name { get; set; } = null!;

    [ForeignKey( "Id" )]
    public long? InstanceOfId { get; set; } = null;
    public ConceptData? InstanceOf { get; set; } = null;

    [ForeignKey( "Id" )]
    public long? PartOfId { get; set; } = null;
    public ConceptData? PartOf { get; set; } = null;
}

The dependent side could not be determined for the one-to-one relationship between 'ConceptData.InstanceOf' and 'ConceptData.PartOf'.

Am I going to have to resort to Fluent API to make these self-referencing keys be accepted?

Also, is this correct (non-redundant) convention for foreign key use in general?

CodePudding user response:

The ForeignKeyAttribute is incorrect. PartOfId and InstanceOfId are your foreign key properties. Id is the PrimaryKey property to which the FKs refer.

  • Related