EF Code The first navigation property for the same table.

I am new to EF and struggling to implement the following scenario. I have an entity that I would like to have a navigation property for another from the same object. For instance.

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 found so far was that the object had parent / child relationships, i.e. The navigation property was an ICollection of the same object. I tried to adapt this, but could not get it to work in my case. In addition, I need only one way, that is, the object does not have the "PreviousStage" property, but simply "NextStage". I am customizing the use of the Fluent API. Can anyone advise as much as possible?

I get this error:

Unable to determine the main end of the relationship between type namespaces. Voltage 'and' namespace.Stage '. The main end of this association must be explicitly configured using a free API or data annotation

Edit Just understood in my simplified example, I did not show that NextStageID is optional (int?).

+5
source share
2 answers

You can explicitly define the relationship 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;} } 
+9
source

you need to add the parentId property and Parent navigation and the navigation property for children, so the entity infrastructure understands that this is a recursive relation check the answer in this link

0
source

Source: https://habr.com/ru/post/1237867/


All Articles