简体   繁体   English

在Neo4jClient中动态使用参数进行关系

[英]Dynamically using params for relationship in Neo4jClient

I am trying to use params to pass in relationship types dynamically with Neo4jclient but it didn't seem to work. 我正在尝试使用params与Neo4jclient动态传递关系类型,但是它似乎没有用。 Is this possible? 这可能吗? Or what would be the equivalent? 或等价的是什么? Basically I am trying to write a utility method to relate two nodes together by simply passing in two node Id and a relationship. 基本上,我试图编写一种实用程序方法,以简单地传入两个节点ID和一个关系来将两个节点关联在一起。 I could potentially hard coded it but I am afraid that is against the best practice and vulnerable to injections. 我可能会对其进行硬编码,但恐怕这违反了最佳实践,并且容易受到注射的影响。 Thanks. 谢谢。

    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;
    }

I don't think you can create a relationship name via parameters, the only way I've ever seen this done in C# is to to use string.Format for the .CreateUnique . 我认为您不能通过参数创建关系名称 ,我在C#看到的唯一方法是对.CreateUnique使用string.Format

If you're worried about injection, one solution could be to use an Enum , so: 如果您担心注入,一种解决方案可能是使用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.");

That way if someone tries to pass in a relationship you're not using ie trying something like AddEdge("blah", (Relationships) 200, "blah2"); 这样,如果有人尝试传递您不使用的relationship ,即尝试类似AddEdge("blah", (Relationships) 200, "blah2"); you can ignore it. 您可以忽略它。

One nice thing you get from this is that you can use the enum directly in your format: 这样做的enum是您可以直接使用格式的enum

...CreateUnique(string.Format("n1-[:{0}]-n2", relationship))

provided you name your values in the Relationships enum as you want them: 只要您愿意,就可以在“ Relationships枚举中命名您的值:

public enum Relationships {
    HAS_A,
    IS_A
    //etc
}

Another bonus is that you don't have to worry about misspelling, as you can use the Relationships enum throughout your code for querying. 另一个好处是,您不必担心拼写错误,因为您可以在整个代码中使用Relationships枚举进行查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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