Zac
Zac

Reputation: 1742

EF Many to many relationship with a navigation property

I have a many to many relationship between nodes in a graph. All connections between nodes are two-way.

Thus I have a table of nodes:

NodeId  |  NodeName
   1          A
   2          B
   3          C
   4          D

And a table of node links:

LeftNodeId  |  RightNodeId
     1              2
     1              4
     2              3
     3              4

So as you can see, my graph looks like:

A - B - C
|       |
 ---D---

When I pull this into an EF model, my Node object will have two navigation properties - Nodes and Node1. Nodes will contain the "left" nodes, and Node1 will contain the "right" nodes.

My question is how best to set up the SQL database so that I only have a single navigation property, e.g. "Neighbours" for neighbouring nodes?

My relationships between nodes are ALWAYS bi-directional.

Upvotes: 0

Views: 168

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

It is "not possible". EF demands to separately maintain both navigation properties. For example if you have node 2 one property will contain relation between 2 and 3 (because 2 is on the left side) and second navigation property will contain relation between 1 and 2 (because 2 is on the right side).

If you need single property showing all relations you can use non mapped computed property:

public IEnumerable<Node> AllRelations
{
    get
    { 
        return LeftRelations.Concat(RightRelations);
    }
}

Upvotes: 1

Related Questions