crud
Creating a Node
As one would expect, creating a node is a rather trivial affair:
var myNodeReference = client.Create(new MyNode { Foo = "bar" });
Note that we've only created an orphaned node for now. We'll work with relationships in the next chapter.
Influencing Serialization
The supplied object instance will be serialized to JSON using the JSON.NET library. If you want to influence this process, you can do so using their attributes:
public class MyNode
{
[JsonProperty("Bar")]
public string Foo { get; set; }
[JsonIgnore]
public string Bar { get; set; }
}
Retrieving a Node
Node retrievable is done using a generic signature:
var myNode = client.Get<MyNode>(myNodeReference);
// myNode.Foo == "bar"
In this example we used the node reference from when we first created the node. Alternatively, you can just supply a neo4j node id directly:
var myNode = client.Get<MyNode>(123);
You won't see this signature in IntelliSense, because it's actually implemented as an implicit cast.
Integer values can be both implicitly and explicitly cast to NodeReference instances:
var nodeRef = (NodeReference)123;
Assert.AreEqual(123, nodeRef.Id);
Generally, you should always use an instance of NodeReference though. This indicates that
you've retrieved it as a result of some other call or query, and not by passing neo4j's internal
node ids around in your application state. (That's a bad idea because they can change.)
Updating a Node
The neo4j REST API requires us to replace the entire node during an update. To reduce the chance of inadvertently repopulating properties with outdated values, the graph client retrieves the node at the last possible moment before giving you a chance to update just the properties that you want to. The entire node is then reserialized and sent back to neo4j.
This technique is achived in code using a callback:
var nodeReference = (NodeReference<MyNode>)123;
graphClient.Update(
nodeReference,
node =>
{
node.Foo = "foo updated";
});
Typed Node References
You'll notice that the last example used NodeReference<TData> as opposed to
NodeReference which was used in the previous examples. Both types are simple containers for
a node id and are easily cast between. The advantage of using typed references is that the C#
compiler will be able to infer method signatures more easily.
In the last example, because we used a typed node reference, the callback argument was
automatically typed to MyNode.
Where possible, preserve typed node references instead of downcasting them to NodeReference.
Deleting a Node
Nodes can be deleted in either NodeOnly or NodeAndRelationships modes:
graphClient.Delete(nodeReference, DeleteMode.NodeOnly);
NodeOnly will throw an exception if the node is still related to any other nodes.
NodeAndRelationships will enumerate and delete each relationship that a node participates
in before finally deleting the node itself.
Updated