Casting nodes of an unknown type

You could (depending on how you feel about it) try using dynamic, for example, you can set it up like so:

var dog = new Dog {Name = "Woofer", Breed = "Afghan Hound"};
var owner = new Person {Name = "Jeff", PhoneNumber = "01234567890"};

//CREATE
gc.Cypher.
    Create("(owner:Person {ownerParams})")
    .WithParam("ownerParams", owner)
    .With("owner")
    .Create("(owner)-[:HAS_PET]->(dog:Dog {dogParams})")
    .WithParam("dogParams", dog)
    .ExecuteWithoutResults();

and retrieve with:

//RETURN
var query = gc.Cypher
    .Match("(p:Person)-[:HAS_PET]->(d:Dog)")
    .Return((p, d) => new {Person = p.As<Node<string>>(), Dog = d.As<Node<string>>()});

var results = query.Results.ToList();
foreach (var result in results)
{
    dynamic p = JsonConvert.DeserializeObject<dynamic>(result.Person.Data);
    dynamic d = JsonConvert.DeserializeObject<dynamic>(result.Dog.Data);

    Console.WriteLine("If you find {0} (a {1}) please call {2} on {3}.", d.Name, d.Breed, p.Name, p.PhoneNumber);
}

Obviously in this case I would know the types I was returning. Now, you’ll notice I’m using Node<string> in this – which generally is frowned upon – the reason I’m using it is that it strips out all the normal stuff neo4j returns back, and separates the Data out – which is really all I’m interested in.

You might be tempted to try doing:

.Return((p,d) => new {Person = p.As<dynamic>(), Dog = d.As<dynamic>()});

but the problem you’ll end up with here is that the Neo4jClient doesn’t deal with dynamic and will actually return it as an object which loses all your properties.

This should at least give you a starting point, if you need help with a specific type of query it’d be worth putting the query up for reference.

Leave a Comment