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

174 Views Asked by At

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!

2

There are 2 best solutions below

1
zackper On BEST ANSWER

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!

0
Luca On

As written here is necessary to add --bolt-server-name-for-init=Neo4j/5.7.0 using the correct version of the Neo4j.Driver version.

In case you are starting memgraph using docker, use the following command:

docker run -it -p 7687:7687 -p 7444:7444 -p 3000:3000 -v mg_lib:/var/lib/memgraph -e MEMGRAPH="--bolt-server-name-for-init=Neo4j/5.7.0" memgraph/memgraph-platform