Letâs build an ASP.NET Core CRUD with NoSQL application.
Iâll be creating a basic CRUD HTTP API (CRUD is Create, Read, Update, Delete). This API will be operating on a gift wishlist: all the items I want you to buy me for my birthday. I wonât be building a UI, but you could use this API with the client-side framework of your choice (like React or Blazor, etc).
This first post will include all the ASP.NET Core NoSQL project setup and configuration database. The next posts will build out the actual CRUD endpoints.
Developer tools youâll need
Iâm using Visual Studio 2022 (Enterprise), but you should be able to follow along okay with JetBrains Rider, VSCode, or whatever you normally use. (If you need help, Iâm happy to assist!)
Iâm also using Couchbase Capella, which is the DBaaS (Database as a Service) Couchbase offering.
Iâve already signed up for a trial account. You can too, go to: https://cloud.couchbase.com/sign-up
The travel-sample bucket is already loaded when you deploy your trial cluster. But Iâm using another bucket that I created called demo.
Inside that bucket, thereâs a _default scope, so Iâll use that. And inside that scope, Iâve created a wishlist collection. (Learn more about scopes and collections in Capella)
CRUD credentials
Youâll also need to create database credentials with read/write access to everything in the demo bucket.
Finally, whitelist the IP address that you will be compiling and running your app from so that you can connect.
Start an ASP.NET Core app
In Visual Studio, select FileâNew âProjectâASP.NET Core Web API. I called it AspNetCoreTutorial.
Iâm using .NET 6, and all the other defaults are fine (notice that OpenAPI, aka Swagger, is enabled).
This process creates a basic shell site.
Next, letâs use NuGet to add the Couchbase .NET SDK (CouchbaseNetClient).
Notes on the .NET SDK
The Couchbase .NET SDK allows us to connect to a Couchbase Cluster. Couchbase is a distributed database, so typically there are several servers (called “nodes”) in a group (called a “cluster”) that all act together. A cluster has one or more “buckets”, which as you saw earlier, contains scopes, which contain collections, which then contain documents.
The data in a bucket is distributed amongst the nodes in the cluster, but itâs treated as a single logical entity by the SDK.
Within a collection, each document has a unique “key” and a JSON “value”.
For the trial version of Capella, there will only be a single node. However, this doesnât affect your code: when nodes are added, the SDK is smart enough to be able to find them on its own.
In production, you will typically have at least three nodes, possibly a few buckets, and as many scopes and collections as you need (within reason).
Dependency Injection
Iâm also going to add the Couchbase.Extensions.DependencyInjection NuGet package. This will provide extension methods to easily add Couchbase capabilities to ASP.NET Coreâs built-in dependency injection.
(This package makes it easier to use Couchbase with ASP.NET Core, but it is optional).
Connect ASP.NET Core to Couchbase Capella
Letâs write some code in the ASP.NET app to connect to the Capella cluster.
In Program.cs, use the extension method on services:
1 2 3 4 5 6 7 8 |
builder.Services.AddCouchbase(x => { Â Â x.ConnectionString = "couchbases://" + "<< Capella connection string >>"; Â Â x.UserName = "svc-wishlist"; Â Â x.Password = "TOP-secret-123!"; Â Â x.HttpIgnoreRemoteCertificateMismatch = true; Â Â x.KvIgnoreRemoteCertificateNameMismatch = true; }); |
(In this example, Iâm hardcoding the connection information, but you can also use the configuration in appsettings.json instead).
One more step: when the application stops, I need it to release any Couchbase resources that .NET is using.
You can register code to execute on lifetime events, such as ApplicationStopped.
1 2 3 4 |
app.Lifetime.ApplicationStopped.Register(() => { app.Services.GetService<ICouchbaseLifetimeService>()?.Close(); }); |
Now, ASP.NET Coreâs dependency injection system will automatically inject the Couchbase objects when we want them.
Data Modeling
Before we write more code, letâs think about the data model. Itâs going to be a very simple model: just the name of an item for the wishlist.
In a NoSQL document database, each piece of data has a key and a JSON value. The key can just be a GUID for our purposes (you could also make it a more meaningful key if you wanted). Each item on the wishlist has a “name“, so thereâs going to be a name field.
Iâll create a C# class to represent an item:
1 2 3 4 5 |
public class WishlistItem { Â Â public Guid? Id { get; set; } Â Â public string Name { get; set; } } |
A really simple model, but because Couchbase does not require a pre-defined schema, adding more fields can be as easy as adding them right here in the C# class.
Letâs go ahead and “prime” the database with a couple of Wishlist items.
Navigate to the wishlist collection in Couchbase Capella and add a couple of documents.
The first document will have a key “3ca6e87e-c3a6-4637-989d-33cbca5002b5“, and Iâll give it a name of “Skyline Chili T-Shirt“.
The second document will have a key “31c9cc33-8dfe-440c-bd1b-bb038939d2e0“, Iâll give it a name of “Joey Votto Jersey“.
You can add other documents if youâd like, but we will eventually build an app where documents are added/changed via the ASP.NET Core app.
Controller for NoSQL CRUD actions
Next, create an ASP.NET Controller for my CRUD operations. I call it GiftsController.
In the constructor, specify an IBucketProvider parameter. This is an object that can be used to get a Bucket from the Couchbase DependencyInjection module. I will use it to get a Bucket object for the demo bucket.
1 2 3 4 5 6 7 8 9 10 11 |
public class GiftsController : Controller { Â Â private readonly IBucketProvider _bucketProvider; Â Â public GiftsController(IBucketProvider bucketProvider) Â Â { Â Â Â Â _bucketProvider = bucketProvider; Â Â } Â Â // ... } |
You can execute the app at this point, just to verify that the connection works. There wonât be any endpoints yet (except the WeatherForecast example that Microsoft put in as an example).
Whatâs next?
We now have an ASP.NET Core project, connected to Couchbase Capella. In the next blog post, weâll get into creating the actual CRUD endpoints.
In the meantime, you can:
- Sign up for a Capella free-trial
- Check out the Couchbase Playground for .NET examples that you can run right in the browser.