CRUD-Operations in RavenDB (.Net Client API)

The four basic operations of persistent storage are CRUD (Create, Read, Update and Delete). With those operations you can manage the full lifecycle of an object from its creation till you destroy it. In RavenDB you can use the .Net Client or the HTTP API. Today we will use C# and a Console Application to manipulate the documents.

This post is part of the RavenDB series. You can find the other parts here:

 

Preparing the Project

The simplest way to add the RavenDB client is the use of NuGet. This package manager will not only fetch the current version of the client but also all its dependencies. All you have to do is to open the package manger console and enter this command:

RavenDB does not force you to modify you classes. You can use simple POCOs (Plain Old CLR Object) who don’t need to know anything about the persistence store you want to use. All we need is a simple class to represent a book:

 

Saving a Book

When working with RavenDB we first need to open a connection to the database server. This connection is represented by the DocumentStore class that need a URL and optionally the name of the database. From the DocumentStore we can get the Session object which we will use for all the operations in RavenDB.

This Session object gives us the transactional functionality and helps us to prepare a set of modifications that are submitted to the database with the SaveChanges() method. To store a book we only need those few lines of code:

We now not only have a simple way to store documents, but we also get an implementation of the Unit of Work pattern for free. This pattern helps us to separate the persistence part from our business logic and will keep bigger applications maintainable.

 

Reading the Book

To read a specific book we can either use its primary key (the ID field) or build a LINQ query. When we load the book by its primary key we will always only get one Book (or nothing) back. Keep in mind that a query can return multiple results and therefore you always should expect a list of return values:

 

Changing the Book

To change an object we need to load it, change it and then tell the session to save the changes:

If we omit the call to SaveChanges() the book will not be modified in the database.

 

Deleting the Book

To end the lifecycle of our book we have to delete it. As we did for changing the book we have to load it first and then use the Delete() method to remove the book:

Again SaveChanges() must be called to submit the modifications.

 

Next

The .Net Client API is the way to go when you use RavenDB in a .Net project. But you can do all the same CRUD operations directly over the HTTP API which I will show you next week.

4 thoughts on “CRUD-Operations in RavenDB (.Net Client API)”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.