Casting nodes of an unknown type

流过昼夜 提交于 2019-11-27 09:51:44

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!