Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading