简体   繁体   中英

How to Add a relationship between two nodes using Neo4jClient with C#

public void AddRelationshipTest()
    {
        var conn = Neo4JConn.Connect();
        Team obj = new Team();
        int id1 = 1, id2 = 2;
        NodeReference<Team> sTm = (NodeReference<Team>)ds.GetNodeReference<Team>(id1, conn, obj);
        NodeReference<Team> dTm = (NodeReference<Team>)ds.GetNodeReference<Team>(id2, conn, obj);

        ReportsToData data = new ReportsToData();
        data.SinceYear = 2008;
        reportsTo relation = new reportsTo(dTm, data);
        conn.CreateRelationship(sTm, relation);



    }

where Get NodeRefernce is a method which returns reference of the node and that is working fine. Team is the class having data members as of the nodes When i am using CreateRelationship it creates a relationship My main concern is that it creates relationship even if there is a relationship already between source and target node. I want to create a unique relationship in between two nodes just like

graphClient.Cypher
.Match("(user1:User)", "(user2:User)")
.Where((User user1) => user1.Id == 123)
.AndWhere((User user2) => user2.Id == 456)
.CreateUnique("user1-[:FRIENDS_WITH]->user2")
.ExecuteWithoutResults();

but here FRIENDS_WITH (any relationship) I have to hard code it so i don't want to use it.

How to do it with Neo4jClient?

I'm not really sure what the problem is, with the .CreateUnique why not just use string.Format or string interpolation to not hard code the relationship?

public void CreateRelationship(IGraphClient graphClient, string relationshipName)
{
    graphClient.Cypher
        .Match("(user1:User)", "(user2:User)")
        .Where((User user1) => user1.Id == 123)
        .AndWhere((User user2) => user2.Id == 456)
        .CreateUnique($"(user1)-[:{relationshipName}]->(user2)") //<-- here
        .ExecuteWithoutResults();
}

obviously that could be:

.CreateUnique(string.Format("(user1)-[:{0}]->(user2)", relationshipName))

or even just use + if you really want:

.CreateUnique("(user1)-[:" + relationshipName + "]->(user2)")

You should definitely be using the Cypher technique though, and not using NodeReference<T>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM