Couchbase Linq Provider

Couchbase

I recently decided to use Couchbase for a personal side project.  The primary reason I chose to use it was because I hadn’t yet.  Simple as that.

Again, this is for a personal side project where I try out different technologies.  The second reason was I was interested in N1QL (pronounced “nickel”) which is the Couchbase Server query language.

I’m not covering installing the Couchbase server.  if you don’t have a Couchbase server installed, check out the offical docs.

Couchbase .NET SDK

The most obvious route for accessing a Couchbase server is by using the the official Couchbase .NET Client.  Looking at the docs, its very simple to store and retrieve a documents.  However, one of the features I was most interested was if it had a Linq provider.  It does not.  Bummer.

Linq2Couchbase

Thankfully I discovered Lin2Couchbase by Couchbase Labs which is a Linq provider to produce N1QL using the official Couchbase .NET SDK.

Grab the NuGet Package

Install-Package Linq2Couchbase

Owin/Katana

My side project is a web app that is self host using Katana and NancyFX.  In order to initialize the Couchbase client, you can use the ClusterHelper in your Startup class.  The reason it is done here is that the it is only required be initialized once.  The cluster helper will create a Cluster object which will later be used to create a BucketContext.

BucketContext

If you are familiar with Entity Framework, the BucketContext from Linq2Couchbase is similar to a DbContext.  It provides an API for querying a Couchbase bucket.

You can now inject IBucketContext into your Nancy Modules or Controllers if using ASP.NET MVC/WebAPI.

Registration

Whichever DI container you are using, you will want to register IBucketContext.  I’m using Unity and my registration as follows.

 POCO

For this example, I’ve created a simple User class.  One important thing to note is that you must specify which property in your class is the key.  You can do so by adding the KeyAttribute.  Also, the Key must be a string.

Save

Adding a new object is pretty straight forward.   Just pass your new object the Save() method on the IBucketContext.

Querying

Using the BucketContext you can query your bucket which is also very straight forward.

Note: If you have just installed Couchbase, you must create a primary index on the bucket you are querying.  Refer to the documentation on how to do so.  This stumbled me a bit at the beginning.  Thankfully the Brant Burnett was kind enough to help me out.

Documentation

The GitHub page for Linq2Couchbase has a ton of goodness.  I highly recommend checking it out if you are interested in couchbase or are looking for linq support.

As of this post, the project looks very active (just recently adding async support) and hopefully I can contribute back.