在Neo4jClient中动态使用params进行关系

时间:2015-06-02 06:18:57

标签: c# neo4j neo4jclient

我正在尝试使用params与Neo4jclient动态传递关系类型,但它似乎不起作用。这可能吗?或者相当于什么?基本上我正在尝试编写一个实用程序方法,通过简单地传递两个节点Id和一个关系将两个节点关联在一起。我可能会对它进行硬编码,但我担心这是违反最佳做法并容易受到注射的。感谢。

    public static async Task<string> AddEdge(string node1Id, string relatioinship, string node2Id, bool directed = false)
    {

            await NeoClient.Cypher
                    .Match("(n1)", "(n2)")
                    .Where((BaseObject n1) => n1.Id == node1Id)
                    .AndWhere((BaseObject n2) => n2.Id == node2Id)
                    .CreateUnique("n1-[:{sRelationName}]->n2")
                    .WithParams(new {sRelationName = relatioinship})
                    .ExecuteWithoutResultsAsync();
            return node1Id;
    }

1 个答案:

答案 0 :(得分:2)

我认为您不能通过参数创建关系名称,我在C#中看到这种情况的唯一方法就是使用{{ 1}}代表string.Format

如果您担心注射,一种解决方案可能是使用.CreateUnique,所以:

Enum

这样一来,如果有人试图传递public enum Relationships { Rel_One, Rel_Two } public static async Task<string> AddEdge(string nodeId1, Relationships relationship, string nodeId2) { if(!Enum.IsDefined(typeof(Relationships), relationship)) throw new ArgumentOutOfRangeException("relationship", relationship, "Relationship is not defined."); 您没有使用即尝试类似relationship的内容,则可以忽略它。

您从中获得的一件好事是,您可以直接使用格式的AddEdge("blah", (Relationships) 200, "blah2");

enum

如果您根据需要在...CreateUnique(string.Format("n1-[:{0}]-n2", relationship)) 枚举中为您的值命名:

Relationships

另一个好处是,您不必担心拼写错误,因为您可以在整个代码中使用public enum Relationships { HAS_A, IS_A //etc } 枚举进行查询。