A newer version of this documentation is available.

View Latest

Start Using the .NET SDK

  • tutorial
    +
    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:

    • Couchbase Capella Sample

    • Local Couchbase Server

    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.

    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.

    #r "nuget: CouchbaseNetClient, 3.4.8"
    
    using System;
    using System.Threading.Tasks;
    using Couchbase;
    
    await new StartUsing().ExampleUsing();
    class StartUsing
    {
        public async Task ExampleUsing()
        {
    
            var cluster = await Cluster.ConnectAsync(
                // Update these credentials for your Local Couchbase instance!
                "couchbase://your-ip",
                "Administrator",
                "password");
    
            // 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 });
            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);
            }
    
        }
    }

    As well as the .NET SDK (see below), and a running instance of Couchbase Server, you will need to load up the Travel Sample Bucket using either the Web interface or the command line.

    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:

    Install-Package CouchbaseNetClient

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

    Prerequisites

    The following code samples assume:

    • Couchbase Capella

    • Local Couchbase Server

    • 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 database 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.
    • Couchbase Server is installed and accessible locally.

    • You have created your own bucket, or loaded the Travel Sample dataset using the Web interface.

    • A user is created with permissions to access your cluster (at least Application Access permissions). See Manage Users, Groups and Roles for more details.

    Couchbase Server uses Role Based Access Control (RBAC) to control access to resources. In this guide we suggest using the Full Admin role created during setup of your local Couchbase Server cluster. For production client code, you will want to use more appropriate, restrictive settings.

    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:

    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.

    • Capella Connection

    • Local Server Connection

    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.

    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.
    var cluster = await Cluster.ConnectAsync(
        // Update these credentials for your Local Couchbase instance!
        "couchbase://your-ip",
        "Administrator",
        "password");

    For developing locally on the same machine as Couchbase Server, your URI can be couchbase://localhost. For production deployments, you will want to use a secure server, with couchbases://.

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

    // 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).

    // 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.

    // 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:

    // 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