Skip to content Skip to sidebar Skip to footer

Ef Code First, Entities With Multiple Relations

Here you can see my reduced entity structure which I would like to store in my Sqlite database. I've a Graph which holds a Set of GraphElements. My Graph consists of Edges, Nodes

Solution 1:

I could find a solution myself which I would like to explain briefly:

It is a matter of a “Many to Many” relationship what I was not able to realize in the first place because I always saw it as a “One to Many” relationship problem. But when you see it like this, it’s pretty simple to solve it. In the current case, you have to extend the model as follows. You have to tell EF to create two mapping tables. This way you can store the relationship between the Node and the GridElements/NeighborNodes in separate DB-mapping-tables called NodeGridElement respectiveNodeNeighborNode.

public class ModelConfiguration
{
    private static void ConfigureGridDataCollectionEntity(DbModelBuilder modelBuilder)
    {
        // Graph
        modelBuilder.Entity<Graph>().ToTable("Base.GraphTable")
             .HasRequired(p => p.GraphElements)
             .WithMany()
             .WillCascadeOnDelete(true);

        // GraphElement
        modelBuilder.Entity<GraphElement>()
           .HasRequired(p => p.Graph)
           .WithMany(graph => graph.GraphElements)
           .WillCascadeOnDelete(false);

        // Node
        modelBuilder.Entity<Node>()
            .HasMany(p => p.ConnectedElements)
            .WithMany()
            .Map(cs =>
            {
                cs.MapLeftKey("NodeId");
                cs.MapRightKey("GridElementId");
                cs.ToTable("NodeGridElement");
            });

        modelBuilder.Entity<Node>()
            .HasMany(p => p.NeighborNodes)
            .WithMany()
            .Map(cs =>
            {
                cs.MapLeftKey("NodeId");
                cs.MapRightKey("NeighborNodeId");
                cs.ToTable("NodeNeighborNode");
            });
    }
}

Post a Comment for "Ef Code First, Entities With Multiple Relations"