Search code examples
c#sql-serverentity-frameworkrecursionlocaldb

How to store a recursive model with entity framework 5.0


I'm new to entity framwork and trying to store the following Model to a Database. I have watched this tutorial. I want to store the following model to the database using code first, but I couldn't get it store this recursive structure. It only stores the initial root node.

My model looks like this:

public abstract class Node : INode
{
    public int NodeId { get; set; }

    public Node()
    {
        Nodes = new List<INode>();
    }

    public INode ParentNode { get; set; }

    public List<INode> Nodes { get; private set; }

    public string Name { get; set; }
}

and the derived subtypes:

public class Module : Node, IModule
{
}

public class Location: Node, ILocation
{
}

The Interfaces are these:

public interface INode
{
    INode ParentNode { get; set; }

    List<INode> Nodes { get; }

    string Name { get; set; }
}

public interface IModule : INode
{
}

public interface ILocation : INode
{
}

This is my DbContext:

public class SqlEntityContext : DbContext
{
    public DbSet<Node> Nodes { get; set; }
}

I then create a model of one parent module node containing two location nodes. If I try to store it with this code

using (var db = new SqlEntityContext())
{
    db.SqlSystemNodes.Add(Root as SqlSystemNode);
    db.SaveChanges();
}

only the root node gets stored to the database. I've tried to give each subtype its own key but with no success. How am I able to store this model to the database, any ideas? Is it even possible?


Solution

  • Have you defined parent - child relation in your db context initializer.

    You initializer should have sth like that:

    modelBuilder.Entity<Node>()
        .HasMany(o => o.Nodes)
        .WithOptional() // or .WithRequired()
        .Map(m => m.MapKey("ParentNodeId"));