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.
Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
Couchbase .NET SDKThe 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.
Linq2CouchbaseThankfully I discovered Lin2Couchbase by Couchbase Labs which is a Linq provider to produce N1QL using the official Couchbase .NET SDK. Grab the NuGet Package
Owin/KatanaMy 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.
BucketContextIf 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.
RegistrationWhichever DI container you are using, you will want to register IBucketContext. I’m using Unity and my registration as follows.
POCOFor 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.
SaveAdding a new object is pretty straight forward. Just pass your new object the Save() method on the IBucketContext.
QueryingUsing 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.