Developer Center » Languages » C# » Code Guides » C# Sample Query Code

C# Sample Query Code

This example demonstrates how to query Neo4j from a .NET application using the ExecutableQuery API and map the query results directly into a strongly-typed C# record. You will learn how to:

  • Connect to a Neo4j database using the .NET Driver
  • Write and execute a parameterized Cypher query
  • Configure the target database and pass parameters
  • Automatically map Neo4j results into a domain object (BookReview)
  • Loop through the mapped results and use them in your application

Code sample

Below is the full code, followed by a complete walkthrough of connecting, querying, mapping, and working with Neo4j data.

using Neo4j.Driver;
using Neo4j.Driver.Mapping;

//Create a driver instance supplying where to connect to and the authentication details
var driverInstance = GraphDatabase.Driver(new Uri("neo4j+s://demo.neo4jlabs.com"),
AuthTokens.Basic("goodreads", "goodreads"));

string queryString = @"MATCH (r:Review)-[:WRITTEN_FOR]->(b:Book)<-[:AUTHORED]-(a:Author)
            WHERE a.name = $name
            RETURN b.title AS Title, r.text AS ReviewText, r.rating As Rating
            ORDER BY r.rating DESC
            LIMIT 20"; 

//Run the Cypher query, supplying it with a target database, required parameters, and //receive back the results mapped to your applications domain specific type.
var bookReviews = await driverInstance
.ExecutableQuery(queryString)
    	.WithConfig(new QueryConfig(database: "goodreads")) 
    	.WithParameters(new {name = "Stephen King"}) 
    	.ExecuteAsync()
    	.AsObjectsAsync<BookReview>(); 

//Do something with the results
bookReviews.ToList().ForEach(br => Console.WriteLine($"Title = {br.Title}")); 

//Domain type declaration
record BookReview(string Title, string ReviewText, int Rating); Code language: C# (cs)

Querying Neo4j Reviews with the .NET Driver

1. Import Required Namespaces

using Neo4j.Driver;
using Neo4j.Driver.Mapping;Code language: C# (cs)

These namespaces provide:

  • Core driver functionality (IDriver, sessions, authentication)
  • Automatic mapping of query results into typed objects

2. Create the Neo4j Driver Instance

var driverInstance = GraphDatabase.Driver(
    new Uri("neo4j+s://demo.neo4jlabs.com"),
    AuthTokens.Basic("goodreads", "goodreads"));Code language: C# (cs)
  • Connects to an encrypted Neo4j instance (neo4j+s://)
  • Uses username/password authentication
  • The driver should typically be created once per application

3. Define Your Cypher Query

string queryString = @"
MATCH (r:Review)-[:WRITTEN_FOR]->(b:Book)<-[:AUTHORED]-(a:Author)
WHERE a.name = $name
RETURN b.title AS Title, r.text AS ReviewText, r.rating As Rating
ORDER BY r.rating DESC
LIMIT 20";Code language: C# (cs)

This query:

  • Finds reviews associated with books written by a given author
  • Uses a parameter $name for dynamic filtering
  • Returns values using aliases that match your BookReview record fields

4. Execute the Query with ExecutableQuery

var bookReviews = await driverInstance
    .ExecutableQuery(queryString)
    .WithConfig(new QueryConfig(database: "goodreads"))
    .WithParameters(new { name = "Stephen King" })
    .ExecuteAsync()
    .AsObjectsAsync<BookReview>();Code language: C# (cs)

Step-by-step:

  • ExecutableQuery creates a query builder
  • WithConfig selects the goodreads database
  • WithParameters safely injects $name
  • ExecuteAsync runs the Cypher query
  • AsObjectsAsync<BookReview>() maps each row into your domain record

5. Use the Results in Your Application

bookReviews.ToList()
    .ForEach(br => Console.WriteLine($"Title = {br.Title}"));Code language: JavaScript (javascript)

The results are:

  • Converted to a list
  • Iterated with a simple foreach
  • Used to print the title of each review result

6. Define Your Domain Model

record BookReview(string Title, string ReviewText, int Rating);Code language: C# (cs)

This record model matches the aliases from RETURN and serves as your strongly-typed representation of each row returned by Neo4j.

Share Article