Connecting to your database with the C# driver

Use the DataStax C# driver to connect to your database created using the DataStax Cloud console.

Use the unified DataStax C# driver to connect to your DataStax Astra database and begin building your own application.
Tip: DataStax recommends using the unified DataStax C# driver. If you have an existing Apache Cassandra or DataStax Enterprise (DSE) C# driver, migrate the driver to a version that is capable of connecting to Astra databases.

Prerequisites

  1. Download and install the current version of the .NET Core SDK.
  2. Download the secure connect bundle to obtain connection credentials for your DataStax Astra database.

Procedure

  1. Create a new C# project and configure it to connect to your Cassandra database.
    mkdir csharpproject
    cd csharpproject
    dotnet new console
    1. Add the dependencies for the C# driver to your project.
      dotnet add package CassandraCSharpDriver -v 3.13.0
    2. Replace the code in Program.cs with the following code to connect to your Astra database.
      Note: Include the absolute path to the secure connect bundle for your Astra database (secure-connect-database_name.zip) in the WithCloudSecureConnectionBundle method call, and your credentials in the WithCredentials method call, as shown in the following examples.
      using System;
      using System.Linq;
      using Cassandra;
      
      namespace csharpproject
      {
          class Program
          {
              static void Main(string[] args)
              {
                  var session = 
                      Cluster.Builder()
                             .WithCloudSecureConnectionBundle(@"C:\path\to\secure-connect-database_name.zip")
                             .WithCredentials("username", "password")
                             .Build()
                             .Connect();               
              }
          }
      }
    3. After the connection code, add the following code to the Main method in Program.cs. This code runs a CQL query, and prints the output to the console.
      var rowSet = session.Execute("select * from system.local");
      Console.WriteLine(rowSet.First().GetValue<string>("cluster_name"));
  2. Run your C# project with the dotnet runtime.
    dotnet restore
    dotnet build
    dotnet run --no-build

What's next

Build your application. See the DataStax C# driver documentation for more information about using the DataStax C# driver.