Search code examples
c#memgraphdbbolt

Memgraph C# Connection Issue (Session NullReferenceException) using Neo4j.Driver


I need to connect to my memgraph server (runs through docker), but any basic example I try ends up with a null reference exception when running any query.

The code I am using is:

public async void DatabaseConnectionTest()
    {
        IDriver driver = GraphDatabase.Driver("bolt://127.0.0.1:7687", AuthTokens.None);
        IAsyncSession session = driver.AsyncSession();
        try
        {
            IResultCursor cursor = await session.RunAsync("CREATE (n: TestNode) RETURN n");
            await cursor.ConsumeAsync();
        }
        catch(Exception e)
        {
            Console.WriteLine($"Exception {e.Message}");
        }
        finally
        {
            await session.CloseAsync();
        }

        await driver.DisposeAsync();
    }

When trying to run this code, I get a "NullReferenceException" to this line:

IResultCursor cursor = await session.RunAsync("CREATE (n: TestNode) RETURN n");

Am I doing something completely wrong? What am I missing.

Thanks in advance!


Solution

  • The problem I was facing was due to wrong configuration file for my memgraph docker container.

    In the documentation of Memgraph (as seen here) it explicitly declares that to use the Neo4J.Driver in you need to apply the following changes.

    In order for the Neo4j driver to work, you need modify configuration setting --bolt-server-name-for-init. When running Memgraph, set --bolt-server-name-for-init=Neo4j/5.2.0. If you use other version of Neo4j driver, make sure to put the appropriate version number.

    Now it works perfectly!