6
votes

I'm new to EF and struggling to implement the following scenario. I have an entity I'd like to have a navigation property to another of the same entity. E.g.

public class Stage {
    public int ID { get; set; }
    public int? NextStageID { get; set; }
    public string Name { get; set; }

    public virtual Stage NextStage { get; set;}
}

The only example I've found so far was where the entity had a parent / child relationship, i.e. the navigation property was an ICollection of the same entity. I tried adapting this but couldn't get it to work in my instance. Also, I only need it to be one way, i.e. the entity doesn't have a 'PreviousStage' property, just a 'NextStage' one. I'm configuring using Fluent API. Could someone advise if / how this can be achieved?

I am getting this error:

Unable to determine the principal end of an association between the types 'namespace.Stage' and 'namespace.Stage'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations

Edit Just realised in my slightly simplified example, I didn't show that NextStageID is optional (int?).

2
I think the relationship should already exist for the above model by convention.galdin
@gldraphael I'm getting this error message: "Unable to determine the principal end of an association between the types 'namespace.Stage' and 'namespace.Stage'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations."Kate
Here's how to setup a FK with fluent configuration.Jasen
Thanks @Jasen ! I had skipped over the .HasMany option as I assumed it would be for relationships with a many at one end or the other. Seems, as that post describes, it's also for relationships not involving a many. Bit odd, but that seems to have done the job! Do you want to post as an answer?Kate

2 Answers

9
votes

You can explicitly define the relation as follows:

public class Stage {
    public int ID { get; set; }
    public int NextStageID { get; set; }
    public string Name { get; set; }

    [ForeignKey("NextStageID ")]
    public virtual Stage NextStage { get; set;}
}
0
votes

you need to add a parentId and Parent navigation property and Children navigation property so entity framework understands that is a recursive relation check the answer in this stack Overflow link