Search code examples
c#neo4jcypherneo4jclient

Neo4j Cypher Client Create Dynamic Objects


At the moment I have to specify what class is needed during the return, is there a way to get all properties and and create a dynamic/anonymous object.

public IEnumerable<Node> GetNodes()
    {
        Console.WriteLine($"Retrieving All Nodes from DB...");
        try
        {
            return graphClient.Cypher
               .Match($"(n:Node)")
               .Return(t => new Node
               {
                   Latitude = Return.As<double>("n.lat"),
                   Longitude = Return.As<double>("n.lon"),
                   Id = Return.As<string>("n.id"),
                   ValA = Return.As<long>("n.valA")
               }).Results;
        }
        catch (Exception ex)
        {
            string error = $"ERROR (Get Node): {ex.ToString()}";
            Console.WriteLine(error);
        }

        return null;
    }

Solution

  • Try with the Neo4J official C# driver and JSON.NET like:

    public static void Main()
    {
        string neo4jHostname = string.Empty, neo4jUsername = string.Empty, neo4jPassword = string.Empty;
        IDriver driver = GraphDatabase.Driver(neo4jHostname, AuthTokens.Basic(neo4jUsername, neo4jPassword));
    
        using (ISession session = driver.Session())
        {
            string query = "MATCH (n) RETURN n";
            IStatementResult resultCursor = session.Run(query);
            List<IRecord> res = resultCursor.ToList();
            string values = JsonConvert.SerializeObject(res.Select(x => x.Values), Formatting.Indented);
            List<JObject> nodes = JsonConvert.DeserializeObject<List<JObject>>(values);
        }
    }