Patrick
Patrick

Reputation: 478

Returning neo4j results to a C# object

I have a query that returns a list of object with properties. Consider a C# object with like this structure:

public class Neo4jResult {
   public string Prop1 { get; set; }
   public string Prop2 { get; set; }
   public string Prop3 { get; set; }
}

The query returns a column called "mycollection" and I can store the results to something like this:

public async Task<IEnumerable<Neo4jResult>> MyNeo4jQuery() {
   var cypher = client.Cypher
      .Match(matchQuery)
      .WithParams(myParams);

   cypher =
      cypher.ReturnDistinct<Neo4jResult>("mycollection")
      .OrderBy("toLower(object.Prop1)");

   var query = (IOrderedCypherFluentQuery<Neo4jResult>)cypher;

   return await query.ResultsAsync;
}

This code works well. However, I had to get the count of this record as another property so my query now returns two columns - "mycollection", and "totalRecords". To facilitate this, I created a new object that reflects this:

public class Neo4jResultNew {
   public int TotalRecords { get; set; }
   public IEnumerable<Neo4jResult> Results { get; set; }
}

I have then changed my neo4j query to something like:

public async Task<IEnumerable<Neo4jResult>> MyComplexNeo4jQuery() {
   var cypher = client.Cypher
      .Match(matchQuery)
      .WithParams(myParams);

   cypher =
      cypher.Return<Neo4jResultNew>( (mycollection, totalRecords) => {
      {
         Results = mycollection.As<IEnumerable<Neo4jResult>>(),
         TotalRecords = totalRecords.As<int>()
      });

   var query = (IOrderedCypherFluentQuery<Neo4jResultNew>)cypher;

   return await query.ResultsAsync;
}

The error returned by neo4j is: "Neo4j returned a valid response, however Neo4jClient was unable to deserialize into the object structure you supplied". I just followed the examples online but there's something missing in my projection maybe?

Upvotes: 0

Views: 848

Answers (1)

Charlotte Skardon
Charlotte Skardon

Reputation: 6270

I think the problem is your:

Results = mycollection.As<IEnumerable<Neo4jResult>>(),

Bit. What you're actually wanting is a COLLECT so something like:

Results = mycollection.CollectAs<Neo4jResult>()

mycollection isn't actually an IEnumerable - and you can see it if you run the query in the browser - you don't put it here, so this is a 'rough' version.

If you executed:

MATCH (m:Movie)
RETURN m.title, count(m)

You'll get:

Title1, 1
Title2, 1
Title3, 1

etc

If you execute:

MATCH (m:Movie)
RETURN COLLECT(m.title), count(m)

You'll get:

[title1, title2, title3], 3

for example.

Upvotes: 1

Related Questions