Quantcast
Viewing all articles
Browse latest Browse all 13

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:

Install-Package RavenDB.Client

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:

public class Book
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string ISBN { get; set; }
    public int Pages { get; set; }
 
    public override string ToString()
    {
        return String.Format("{0}: '{1}' ISBN: {2} ({3} pages)", 
            Id, Title, ISBN, Pages);
    }
}

 

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:

using (var documentStore = new DocumentStore 
    { Url = "http://localhost:8080", 
      DefaultDatabase = "Demo" }.Initialize())
using (var session = documentStore.OpenSession())
{
    var book = new Book{ Title = "RavenDB Intro", ISBN = "1", Pages = 200 };

    session.Store(book);
    session.SaveChanges();

    Console.WriteLine(book.Id); //prints: books/1
}

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:

using (var documentStore = new DocumentStore
{
    Url = "http://localhost:8080",
    DefaultDatabase = "Demo"
}.Initialize())
using (var session = documentStore.OpenSession())
{
    // by ID
    var book = session.Load<Book>("books/1");
    Console.WriteLine(book); 
    // prints: books/1: 'RavenDB Intro' ISBN: 1 (200 pages)


    // by LINQ query
    var ravenBooks = from books in session.Query<Book>()
                        where books.Title.StartsWith("Raven")
                        select books;

    foreach (var foundBook in ravenBooks)
    {
        Console.WriteLine(foundBook.Id + ": " + foundBook.Title);
        // prints: books/1 : RavenDB Intro
    }
}

 

Changing the Book

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

using (var documentStore = new DocumentStore
{
    Url = "http://localhost:8080",
    DefaultDatabase = "Demo"
}.Initialize())
using (var session = documentStore.OpenSession())
{
    var book = session.Load<Book>("books/1");
    Console.WriteLine(book);
    // prints: books/1: 'RavenDB Intro' ISBN: 1 (200 pages)
 
    book.Title = "Another Book about RavenDB";
    session.SaveChanges();
 
    var renamedBook = session.Load<Book>("books/1");
    Console.WriteLine(renamedBook);
    // prints: books/1: 'Another Book about RavenDB' ISBN: 1 (200 pages)
}

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:

using (var documentStore = new DocumentStore
{
    Url = "http://localhost:8080",
    DefaultDatabase = "Demo"
}.Initialize())
using (var session = documentStore.OpenSession())
{
    var book = session.Load<Book>("books/1");
 
    session.Delete(book);
    session.SaveChanges();
}

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.

The post CRUD-Operations in RavenDB (.Net Client API) appeared first on Improve & Repeat.


Viewing all articles
Browse latest Browse all 13

Trending Articles