繁体   English   中英

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

[英]Dynamically using params for relationship in 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;
    }

我认为您不能通过参数创建关系名称 ,我在C#看到的唯一方法是对.CreateUnique使用string.Format

如果您担心注入,一种解决方案可能是使用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是您可以直接使用格式的enum

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

只要您愿意,就可以在“ Relationships枚举中命名您的值:

public enum Relationships {
    HAS_A,
    IS_A
    //etc
}

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

暂无
暂无

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

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