Search code examples
graph-databasesmemgraphdb

How can I connect to Memgraph from my C# application?


I have data stored in dockerized Memgraph database. How can I connect from my C# app to the database?


Solution

  • You have to use Neo4j.Driver.Simple package which implements a blocking interface around the 'main' driver.

    Once you have the latest version of driver installed you can connect to your database using one of the ways.

    First way:

    using System;
    using System.Linq;
    using Neo4j.Driver;
    
    namespace MemgraphApp
    {
        public class Program
        {
            public static void Main()
            {
                string message = "Hello, World!";
    
                using var _driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.None);
                using var session = _driver.Session();
    
                var greeting = session.WriteTransaction(tx =>
                {
                    var result = tx.Run("CREATE (n:FirstNode) " +
                                        "SET n.message = $message " +
                                        "RETURN 'Node '  + id(n) + ': ' + n.message",
                        new { message });
                    return result.Single()[0].As<string>();
                });
                Console.WriteLine(greeting);
            }
        }
    }
    

    Second way:

    using System;
    using System.Linq;
    using Neo4j.Driver;
    
    namespace MemgraphApp
    {
        public class Program : IDisposable
        {
            private readonly IDriver _driver;
    
            public Program(string uri, string user, string password)
            {
                _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
            }
    
            public void PrintGreeting(string message)
            {
                using (var session = _driver.Session())
                {
                    var greeting = session.WriteTransaction(tx =>
                    {
                        var result = tx.Run("CREATE (n:FirstNode) " +
                                            "SET n.message = $message " +
                                            "RETURN 'Node '  + id(n) + ': ' + n.message",
                            new { message });
                        return result.Single()[0].As<string>();
                    });
                    Console.WriteLine(greeting);
                }
            }
    
            public void Dispose()
            {
                _driver?.Dispose();
            }
    
            public static void Main()
            {
                using (var greeter = new Program("bolt://localhost:7687", "", ""))
                {
                    greeter.PrintGreeting("Hello, World!");
                }
            }
        }
    }
    

    Detailed instructions can be found at https://memgraph.com/docs/memgraph/connect-to-memgraph/drivers/c-sharp.