Couchbase Server Quickstart - .NET Core with Linq2Couchbase First Query

    +
    Using the Couchbase .NET SDK in a .NET Core console application to create new database records in Couchbase and look them up with Linq2Couchbase.

    Prerequisite: Run Couchbase Server

    1. Couchbase Server 6.5 is already running.

      • An empty bucket named "default" has been created.

      • Both a primary index and an adaptive index have been created and built on the default bucket.

      • If you still need to perform these tasks please use the following:

    2. Visual Studio Code is installed. This tutorial uses Visual Studio Code 1.44.

    3. .NET Core Runtime is installed. This tutorial uses .NET Core 3.1

    Step 1: Start a New .NET Core Project

    From a command line, use dotnet new to create a new project. For this quickstart, we’ll be creating a simple console application:

    dotnet new console -n FirstQuery

    After executing that command, you should see an output similar to this:

    The template "Console Application" was created successfully.
    
    Processing post-creation actions...
    Running 'dotnet restore' on FirstQuery\FirstQuery.csproj...
      Restore completed in 137.68 ms for C:\your\folder\here\FirstQuery\FirstQuery.csproj.
    
    Restore succeeded.

    Open this folder with Visual Studio Code by using File→Open Folder.

    Open Folder in Visual Studio Code

    When you open the folder, you should see the contents of the folder, including Program.cs.

    Folder contents in Visual Studio Code

    Program.cs is where we will be doing all the coding for this exercise. It should currently contain a "Hello, World" example like this:

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
    }

    Next, install the Linq2Couchbase package from NuGet. On the command line:

    dotnet add package Linq2Couchbase --version 1.4.2

    After running this, you should see an output similar to:

      Writing C:\Users\mgroves\AppData\Local\Temp\tmp4C1A.tmp
    info : Adding PackageReference for package 'Linq2Couchbase' into project 'C:\your\folder\here\FirstQuery\FirstQuery.csproj'.
    info : Restoring packages for C:\your\folder\here\FirstQuery\FirstQuery.csproj...
    info : Package 'Linq2Couchbase' is compatible with all the specified frameworks in project 'C:\your\folder\here\FirstQuery\FirstQuery.csproj'.
    info : PackageReference for package 'Linq2Couchbase' version '1.4.2' added to file 'C:\your\folder\here\FirstQuery\FirstQuery.csproj'.
    info : Committing restore...
    info : Generating MSBuild file C:\your\folder\here\FirstQuery\obj\FirstQuery.csproj.nuget.g.props.
    info : Writing assets file to disk. Path: C:\your\folder\here\FirstQuery\obj\project.assets.json
    log  : Restore completed in 1.26 sec for C:\your\folder\here\FirstQuery\FirstQuery.csproj.

    Step 2: Cluster and Linq Setup

    First, in Main, create a Couchbase cluster object to connect to Couchbase Server and create a bucket object:

    var cluster = new Cluster(new ClientConfiguration {
        Servers = new List<Uri> { new Uri("http://localhost:8091")}
    });
    cluster.Authenticate("Administrator", "password");
    var bucket = cluster.OpenBucket("default");
    For this simple console app, I’m hardcoding the credentials, but you should consider using a config file.

    Using the bucket object, create a Linq2Couchbase context object:

    var context = new BucketContext(bucket);

    Make sure to call cluster.Dispose() at the end of Main to close and dispose any resources used in connecting to Couchbase.

    Step 3: Create new documents

    Create a C# class that will correspond to the document that we will be creating:

    public class User
    {
        public string Email {get;set;}
        public string FirstName {get;set;}
        public string LastName {get;set;}
        public string TagLine {get;set;}
        public string Type {get;} = "user";
    }

    Now create instances of this object, and give them some values. Use bucket.Upsert to put this data into the Couchbase bucket.

    "Upsert" will either create a new document or update an existing document. "Insert" will create a document, but fail if it already exists. "Replace" will update a document, but fail if it doesn’t exist.
    var user00001 = new User {
        Email = "perry.mason@acme.com",
        FirstName = "Perry",
        LastName = "Mason",
        TagLine = "Who can we get on the case?"
    };
    var user00002 = new User {
        Email = "major.tom@acme.com",
        FirstName = "Major",
        LastName = "Tom",
        TagLine = "Send me up a drink"
    };
    var user00003 = new User {
        Email = "jerry.wasaracecardriver@acme.com",
        FirstName = "Jerry",
        LastName = "Wasaracecardriver",
        TagLine = "el sob number one"
    };
    bucket.Upsert("USER::00001", user00001);
    bucket.Upsert("USER::00002", user00002);
    bucket.Upsert("USER::00003", user00003);

    Try executing this program now by running dotnet run from the command line. After the program finishes executing, there should be 3 documents in the default bucket.

    Step 4: Linq2Couchbase

    Open the Query Workbench in the Couchbase UI. Enter a query to select everything from the default bucket:

    SELECT d.*
    FROM default d

    You should see the inserted documents in the results:

    [
      {
        "email": "perry.mason@acme.com",
        "firstName": "Perry",
        "lastName": "Mason",
        "tagLine": "Who can we get on the case?",
        "type": "user"
      },
      {
        "email": "major.tom@acme.com",
        "firstName": "Major",
        "lastName": "Tom",
        "tagLine": "Send me up a drink",
        "type": "user"
      },
      {
        "email": "jerry.wasaracecardriver@acme.com",
        "firstName": "Jerry",
        "lastName": "Wasaracecardriver",
        "tagLine": "el sob number one",
        "type": "user"
      }
    ]

    Instead of writing a query directly, let’s query these documents with Linq2Couchbase. Use the context.Query<> method to query documents with the standard Linq extension methods. To query by first name, for instance:

    var results = context.Query<User>().Where(u => u.FirstName == "Perry");
    
    foreach(var result in results)
    {
        Console.WriteLine($"{result.FirstName} {result.LastName} {result.Email}");
        Console.WriteLine($"{result.TagLine}");
        Console.WriteLine();
    }

    Run the program (again with dotnet run) and the output should appear like so:

    Perry Mason perry.mason@acme.com
    Who can we get on the case?

    Feel free to add your own users and try your own Linq queries.

    Done

    Here is the complete Startup.cs.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Couchbase;
    using Couchbase.Configuration.Client;
    using Couchbase.Linq;
    
    namespace FirstQuery
    {
        class Program
        {
            static void Main(string[] args)
            {
                // tag::clusterSetup[]
                var cluster = new Cluster(new ClientConfiguration {
                    Servers = new List<Uri> { new Uri("http://localhost:8091")}
                });
                cluster.Authenticate("Administrator", "password");
                var bucket = cluster.OpenBucket("default");
                // end::clusterSetup[]
    
                // tag::linqSetup[]
                var context = new BucketContext(bucket);
                // end::linqSetup[]
    
                // tag::upserts[]
                var user00001 = new User {
                    Email = "perry.mason@acme.com",
                    FirstName = "Perry",
                    LastName = "Mason",
                    TagLine = "Who can we get on the case?"
                };
                var user00002 = new User {
                    Email = "major.tom@acme.com",
                    FirstName = "Major",
                    LastName = "Tom",
                    TagLine = "Send me up a drink"
                };
                var user00003 = new User {
                    Email = "jerry.wasaracecardriver@acme.com",
                    FirstName = "Jerry",
                    LastName = "Wasaracecardriver",
                    TagLine = "el sob number one"
                };
                bucket.Upsert("USER::00001", user00001);
                bucket.Upsert("USER::00002", user00002);
                bucket.Upsert("USER::00003", user00003);
                // end::upserts[]
    
                // tag::linq[]
                var results = context.Query<User>().Where(u => u.FirstName == "Perry");
    
                foreach(var result in results)
                {
                    Console.WriteLine($"{result.FirstName} {result.LastName} {result.Email}");
                    Console.WriteLine($"{result.TagLine}");
                    Console.WriteLine();
                }
                // end::linq[]
    
                cluster.Dispose();
            }
        }
    
        // tag::user[]
        public class User
        {
            public string Email {get;set;}
            public string FirstName {get;set;}
            public string LastName {get;set;}
            public string TagLine {get;set;}
            public string Type {get;} = "user";
        }
        // end::user[]
    }

    Be sure to check out the other quick start exercises. The complete source code is available on GitHub.