Install and Start Using the .NET SDK with Couchbase Server

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

    Installing the SDK

    The Couchbase .NET SDK is compatible with .NET Standard 2.0 and .NET Standard 2.1, which means that it is compatible with .NET Framework 4.6.2+, .NET 5.0, .NET 6.0, and .NET Core 3.1. The .NET Standard documentation and .NET Standard version chart may be useful to help understand other available options.

    We strongly recommend using the latest version of .NET that is officially supported by Microsoft. Other .NET implementations might work but are not tested and are outside of the scope for technical support. See the Compatibility section for more details.

    The library is distributed in a number of ways:

    NuGet

    NuGet package host at nuget.org (recommended)

    Zip

    Zip files for each release are linked from the Release Notes here.

    Build from Source

    Build the library from source available on GitHub (not officially supported)

    Hello Couchbase

    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.

    Install the latest 3.2 CouchbaseNetClient NuGet package.

    The following code samples assume:

    • Couchbase Server is installed and accessible locally (Do a Quick Install if you don’t already have Couchbase Server installed).

    • You have create a bucket (perhaps using the travel-sample dataset, or by creating a new bucket).

    • You have created a Couchbase user named "username" with permissions to access the cluster (at least Application Access permissions).

    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;

    Then you can connect to the cluster:

    var cluster = await Cluster.ConnectAsync("couchbase://localhost", "username", "password");

    Couchbase uses Role Based Access Control (RBAC) to control access to resources. If you’re developing client code on the same machine as the Couchbase Server, your URI can be couchbase://localhost.

    Then open the bucket:

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

    Substitute whatever bucket name you want for bucket-name in the above example.

    The 3.2 SDK is ready for the introduction of Collections in the 7.0 release of the Couchbase Data Platform. The latest release, Couchbase Server 7.0, brings Collections, allowing Documents to be grouped by purpose or theme, according to specified Scope.

    // get a user-defined collection reference
    var scope = await bucket.ScopeAsync("tenant_agent_00");
    var collection = await scope.CollectionAsync("users");
    This feature was previously avaiable as a developer preview from Couchbase Server 6.6. When connecting to a 6.6 cluster or earlier, we must use the DefaultCollection, which covers the whole Bucket.

    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>());

    Other possible key/value CRUD Operations are described in detail on the KV Operations page.

    You can also perform a N1QL query with the cluster object:

    // Call the QueryAsync() function on the cluster object and store the result.
    var queryResult = await cluster.QueryAsync<dynamic>("select \"Hello World\" as greeting");
    
    // 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 N1QL queries on the Query page.

    Full Example

    If you want to copy and paste to run the full example, here it is:

    • Local Couchbase Server

    • Couchbase Capella Sample

    using System;
    using System.Threading.Tasks;
    using Couchbase;
    
    namespace examples
    {
        class StartUsing
        {
            static async Task Main(string[] args)
            {
    
                 var cluster = await Cluster.ConnectAsync("couchbase://localhost", "username", "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 cluster object and store the result.
                var queryResult = await cluster.QueryAsync<dynamic>("select \"Hello World\" as greeting");
                
                // Iterate over the rows to access result data and print to the terminal.
                await foreach (var row in queryResult) {
                    Console.WriteLine(row);
                }
    
            }
        }
    }

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

    using System;
    using System.Threading.Tasks;
    using Couchbase;
    using Couchbase.Query;
    using Couchbase.Management.Query;
    // using Microsoft.Extensions.DependencyInjection;
    // using Microsoft.Extensions.Logging;
    // using Serilog;
    // using Serilog.Extensions.Logging;
    
    namespace net3
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                // Update this to your cluster
                var endpoint = "cb.13d1a4bc-31a8-49c6-9ade-74073df0799f.dp.cloud.couchbase.com";
                var bucketName = "couchbasecloudbucket";
                var username = "user";
                var password = "password";
                // User Input ends here.
    
                // IServiceCollection serviceCollection = new ServiceCollection();
                // serviceCollection.AddLogging(builder => builder.AddFilter(level => level >= LogLevel.Trace));
    
                // var loggerFactory = serviceCollection.BuildServiceProvider().GetService<ILoggerFactory>();
                // loggerFactory.AddFile("Logs/myapp-{Date}.txt", LogLevel.Debug);
    
                // Initialize the Connection
                var opts = new ClusterOptions().WithCredentials(username, password);
                // opts = opts.WithLogging(loggerFactory);
                opts.IgnoreRemoteCertificateNameMismatch = true;
    
                var cluster = await Cluster.ConnectAsync("couchbases://"+endpoint, opts);
                var bucket = await cluster.BucketAsync(bucketName);
                var collection = bucket.DefaultCollection();
    
                // Store a Document
                var upsertResult = await collection.UpsertAsync("king_arthur", new {
                    Name = "Arthur",
                    Email = "kingarthur@couchbase.com",
                    Interests = new[] { "Holy Grail", "African Swallows" }
                });
    
                // Load the Document and print it
                var getResult = await collection.GetAsync("king_arthur");
                Console.WriteLine(getResult.ContentAs<dynamic>());
    
                // Perform a N1QL Query
                var queryResult = await cluster.QueryAsync<dynamic>(
                    String.Format("SELECT name FROM `{0}` WHERE $1 IN interests", bucketName), 
                    new QueryOptions().Parameter("African Swallows")
                );
    
                // Print each found Row
                await foreach (var row in queryResult)
                {
                    Console.WriteLine(row);
                }
            }
        }
    }

    Cloud Connections

    For developing on Couchbase Capella, if you are not working from the same Availability Zone, refer to the follorwing:

    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.