![](/img/trans.png)
[英]How get relationship's startNodeId and endNodeId using 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.