January 19, 2025
+ 12
The Couchbase .NET SDK enables you to interact with a Couchbase Server cluster from .NET using C# and other .NET languages. It offers an asynchronous API based on the Task-based Asynchronous Pattern (TAP).

The Couchbase .NET client allows applications to connect to Couchbase Server using any Common Language Runtime (CLR) language, including C#, F#, and VB.NET. The SDK is written in C#, and some of its idiomatic patterns reflect that choice.

In this guide, you will learn:

Hello Couchbase

We will go through the code sample step by step, but for those in a hurry to see it, here it is:

If you are connecting to Couchbase Capella, be sure to get the correct endpoint as well as user, password — and see the Cloud section, below.

csharp
using System; using System.Threading.Tasks; namespace Couchbase.Net.DevGuide.Cloud; public class Progam { public static async Task Main(string[] args) { await new CloudExample().Main(); } } class CloudExample { public async Task Main() { var options = new ClusterOptions { // Update these credentials for your Capella instance UserName = "username", Password = "Password!123", }; // Sets a pre-configured profile called "wan-development" to help avoid latency issues // when accessing Capella from a different Wide Area Network // or Availability Zone (e.g. your laptop). options.ApplyProfile("wan-development"); var cluster = await Cluster.ConnectAsync( // Update these credentials for your Capella instance "couchbases://cb.<your-endpoint>.cloud.couchbase.com", options ); // get a bucket reference var bucket = await cluster.BucketAsync("travel-sample"); // get a user-defined collection reference var scope = await bucket.ScopeAsync("tenant_agent_00"); var collection = await scope.CollectionAsync("users"); // Upsert Document var upsertResult = await collection.UpsertAsync("my-document-key", new { Name = "Ted", Age = 31 }); using var getResult = await collection.GetAsync("my-document-key"); Console.WriteLine(getResult.ContentAs<dynamic>()); // Call the QueryAsync() function on the scope object and store the result. var inventoryScope = bucket.Scope("inventory"); var queryResult = await inventoryScope.QueryAsync<dynamic>("SELECT * FROM airline WHERE id = 10"); // Iterate over the rows to access result data and print to the terminal. await foreach (var row in queryResult) { Console.WriteLine(row); } } }

The Couchbase Capella free tier version comes with the Travel Sample Bucket, and its Query indexes, loaded and ready.

Installing the SDK

The Couchbase .NET SDK is compatible with .NET Standard 2.0 and .NET Standard 2.1, via the currently supported Microsoft .NET SDKs. Currently, that includes .NET 6.0 and later for .NET Standard 2.1 and .NET Framework 4.6.2 and later for .NET Standard 2.0. The .NET Standard documentation and .NET Standard version chart may be useful to help understand other available options.

Couchbase strongly recommends using the latest LTS version of .NET that’s officially supported by both Microsoft and Couchbase. Other .NET implementations may work, but aren’t tested, and are outside the scope of technical support. See the Compatibility section for more details.

Quick Installation

The quickest way to get up and running is with NuGet, from the Package Manager Console, within your project:

  1. From the Visual Studio menu bar, click Tools.

  2. Select NuGet Package Manager > Package Manager Console.

  3. In the console, enter the package installation command:

    • To install the latest version:

console
Install-Package CouchbaseNetClient

All other installation methods can be found in our full installation guide.

Prerequisites

The following code samples assume:

  • You have signed up to Couchbase Capella.

  • You have created your own bucket, or loaded the Travel Sample dataset. Note, the Travel Sample dataset is installed automatically when deploying a Capella free tier cluster.

  • A user is created with permissions to access the cluster (at least Application Access permissions). See the Capella connection page for more details.

Couchbase Capella uses Roles to control user access to cluster resources. For the purposes of this guide, you can use the Organization Owner role automatically assigned to your account during installation of the Capella cluster. In a production scenario, we strongly recommend setting up users with more granular access roles as a best practice.

Step by Step

Start a new console project (in Visual Studio or VS Code, etc). Go to our Platform Introduction if you don’t already have an editor or IDE setup for working in .NET — e.g. you are evaluating the .NET SDK, but .NET is not your normal platform.

Firstly, you will need to have a few using statements at the top of Program.cs in your console program:

csharp
using System.Threading.Tasks; using Couchbase;

Connect

Connect to your cluster by calling the Cluster.ConnectAsync() method and pass it your connection details. The basic connection details that you’ll need are given below — for more background information, see Managing Connections.

From version 3.3, the .NET SDK includes Capella’s standard certificates by default, so you do not need to additional configuration. You do need to enable TLS, which can be done by simply using couchbases:// in the connection string as in this example.

csharp
var options = new ClusterOptions { // Update these credentials for your Capella instance UserName = "username", Password = "Password!123", }; // Sets a pre-configured profile called "wan-development" to help avoid latency issues // when accessing Capella from a different Wide Area Network // or Availability Zone (e.g. your laptop). options.ApplyProfile("wan-development"); var cluster = await Cluster.ConnectAsync( // Update these credentials for your Capella instance "couchbases://cb.<your-endpoint>.cloud.couchbase.com", options );

When accessing Capella from a different Wide Area Network or Availability Zone, you may experience latency issues with the default connection settings. SDK 3.4 introduces a wan-development Configuration Profile, which provides pre-configured timeout settings suitable for working in high latency environments. Basic usage is shown in the example above, but if you want to learn more see Constrained Network Environments.

The Configuration Profiles feature is currently a Volatile API and may be subject to change.

Following successful authentication, add this code snippet to access your Bucket:

csharp
// get a bucket reference var bucket = await cluster.BucketAsync("travel-sample");

Add and Retrieve Documents

Collections allow Documents to be grouped by purpose or theme, according to specified Scope. Our Travel Sample bucket has separate scopes for inventory (flights, etc.), and for tenants (different travel agents).

csharp
// get a user-defined collection reference var scope = await bucket.ScopeAsync("tenant_agent_00"); var collection = await scope.CollectionAsync("users");

Data operations, like storing and retrieving documents, can be done using simple methods on the Collection class such as Collection.GetAsync() and Collection.UpsertAsync().

To get you started the following code creates a new document in a custom scope and collection and then fetches it again, printing the result.

csharp
// Upsert Document var upsertResult = await collection.UpsertAsync("my-document-key", new { Name = "Ted", Age = 31 }); var getResult = await collection.GetAsync("my-document-key"); Console.WriteLine(getResult.ContentAs<dynamic>());

SQL++ Lookup

Couchbase SQL++ queries can be performed at the Cluster or Scope level by invoking Cluster.QueryAsync() or Scope.QueryAsync().

Cluster level queries require you to specify the fully qualified keyspace each time (e.g. travel-sample.inventory.airline). However, with a Scope level query you only need to specify the Collection name — which in this case is airline:

csharp
// Call the QueryAsync() function on the scope object and store the result. var inventoryScope = bucket.Scope("inventory"); var queryResult = await inventoryScope.QueryAsync<dynamic>("SELECT * FROM airline WHERE id = 10"); // Iterate over the rows to access result data and print to the terminal. await foreach (var row in queryResult) { Console.WriteLine(row); }

You can learn more about SQL++ queries on the Query page.

Next Steps

Now you’re up and running, try one of the following:

Additional Resources

The API reference is generated for each release. Older API references are linked from their respective sections in the Release Notes.

The Migrating from SDK2 to 3 page highlights the main differences to be aware of when migrating your code from our earlier 2.x .NET SDK.

Troubleshooting

Output