0

I am trying to describe a tree like structure where each item is a node in the tree and can (or not) have a parent.

When describing the Node entity, this works:

public class Node
{
    public int Id {get;set;}
    public string Description {get;set;}
    public int ParentId {get;set;}
}

I get a table called Nodes with the above columns and a PK on Id. If I then add a new parameter:

public virtual Node Parent {get;set;}

for quick/easy access to the parent node, the creation code adds a foreign key constraint requiring ParentId to point to a Node Id.

Since some nodes will not have a parent, attempting to add a Node with a ParentId of 0 fails.

Is there a way to do this?

2
  • 2
    You could use int? as data type for ParentId which means that the parent id is optional and null when a node doesn't have a parent. Commented Apr 23, 2015 at 19:28
  • Have you thought about making ParentId a nullable int? Commented Apr 23, 2015 at 19:30

1 Answer 1

2

do you have any restriction in your data model? if not just try to make parentId nullable as this:

   public int? ParentId {get;set;}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.