0

I created these classes in order to create a tree (user hold the root)

public class Node
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey("Id")]
    public Node Parent_Id { get; set; }
}

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey("Id")]
    public Node Root { get; set; }
}

but the entity framework (code first) doesnt save the parent_id (in the user class it save the "root" as expected)

when i created the tables manually (databese first) as it should be, the entity framework save the parent id as int and not "Node"

what can i do?

1
  • Why do you call it Parent_Id and not simply Parent? I haven't used EF in a while but maybe there is some convention for naming your properties? Commented Nov 6, 2014 at 18:54

1 Answer 1

1

You're not correctly implementing the ForeignKey annotation. You would need to do something like this instead:

[Key]
public int Id { get; set; }
public string Name { get; set; }

public int ParentID { get; set; }

[ForeignKey("ParentID")]
public Node Parent { get; set; }

This code above will then allow you to have separate Nodes that will then be able to have a Parent node assigned to them. Each Node needs to have its own ID, plus that of its Parent. The ForeignKey annotation must point to the Parent's ID, not the Node's.

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.