Casting a Node to a c# object

Hey Neo / C# units... Now that Neo4JClient is obselete (hasn't been updated in over a year) I assume new devs like me are using bolt 4.0. I'm looking for a nice way to cast a node or relationship into one of my c# objects and this is the best solution I can find out there:

        var result = tx.Run(statementText);
        foreach(var record in result)
        {
            var nodeProps = JsonConvert.SerializeObject(record[0].As<INode>().Properties);
            users.Add(JsonConvert.DeserializeObject<User>(nodeProps));
        }

I've gotta think there's a better / more efficient way than the example above. Thx all!

I know this is old, but the way I implement it is like this:

var result = await _session.RunAsync("MATCH (u:User) RETURN u");
        return await result.ToListAsync(record =>
        {
            var node = record["u"].As<INode>();
            return JsonSerializer.Deserialize<User>(
                JsonSerializer.Serialize(node.Properties)
            ) ?? new User();
        });

You could also write an extension method on INode for something like this:

public static T ToObject<T>(this INode node)
    {
        return System.Text.Json.JsonSerializer.Deserialize<T>(
                System.Text.Json.JsonSerializer.Serialize(node.Properties)
            ) ?? default;
    }

Then, you just call it like this:

var node = record[0].As<INode>();
var user = node.ToObject<User>();

Some times you have to be "less purist" at the edge of your tools.

For example for a very complex query returning nodes and relationship - it turned out to be significantly faster and less bandwidth intensive to run a COLLECT() of the nodes and relationships than returning nodes/relationships.

1 Like