Working With RavenDB in MVC Application

Dheeraj Kumar Gunti

Reading Time : ( words)

Hi All,

Welcome back to Knowledge Base.

Today we will see an example to work with RavenDB, NoSQL DB is the one more alternative for traditional db. There are different flavours in NoSQL DB like DynamoDB, mongoDb, CouchDB etc. In this article we will see how to work with RavenDB.

RavenDB is one kind of Document type database, It is opensource and its transactional database. NoSQL DB's are used to build high performance applications effectively. Data is stored in the form of JSON documents and can be queried using LINQ.

Now we will see how to work with RavenDB in MVC application.

Create a basic MVC Application and Open Nuget Package Manager and Install the below packages.

PM> Install-Package RavenDB.Client
PM> Install-Package RavenDB.Server

Once the packages are installed. Go to Packages folder in WebApplication solution directory. Open RavenDb.Server folder and in the open tools folder. Run RavenDb.Server.exe file. It opens in console and It runs RavenDB Server in port 8080. You will see server running in http://localhost:8080. As its in development machine it runs on this port. If you are hosting in different server then providing that server information while working in the application.


Open the url and RavenDB Management Studio will open.

Click on Manage Your Server and Click on To System Database. Once you click on To System Database, then system prompt with alert. Click on OK.




Create a Entity in the MVC application as below.

public class Album
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Genre { get; set; }
    [Required]
    public string ReleaseDate { get; set; }
}

Create a controller,

Initialize DocumentStore class object in the constructor.

DocumentStore documentStore = null;
public AlbumController()
{
            documentStore = new DocumentStore
    {
                Url = "http://localhost:8080"
    };
            documentStore.Initialize();
}

DocumentStore.OpenSession is used to initiate a session for the specific transaction which is similar to the way we work with DbContext in Entityframework. We can perform all the operations using the session object.

Write action method Index to list all the albums.

public ActionResult Index()
{
    using (var session = documentStore.OpenSession())
    {
    var booksData = session.Query<Album>().ToList();
    return View(booksData);
    }
}

AddView Index to the application and Run the application.

Write action method Create to create a new album. AddView Create to the application and Run the application.

public ActionResult Create()
{
    return View();
}
[HttpPost]
public ActionResult Create(Album album)
{
    if (ModelState.IsValid)
    {
    using (var session = documentStore.OpenSession())
    {
             session.Store(album);
             session.SaveChanges();
    return RedirectToAction("Index");
    }
    }
    return View();
}

Check the Documents in the Server with data.

Write action method Edit to Edit album. AddView Edit to the application and Run the application.

public ActionResult Edit(int? id)
{
    using (var session = documentStore.OpenSession())
    {
    var bookData = session.Load<Album>(id);
    return View(bookData);
    }
}
[HttpPost]
public ActionResult Edit(Album album)
{
    using (var session = documentStore.OpenSession())
    {
    var albumData = session.Load<Album>(album.Id);
        albumData.Title = album.Title;
        albumData.Genre = album.Genre;
        albumData.ReleaseDate = album.ReleaseDate;
        session.Store(albumData);
        session.SaveChanges();
    return RedirectToAction("Index");
    }
}


Delete document

public ActionResult Delete(int? id)
{
    using (var session = documentStore.OpenSession())
    {
    var bookData = session.Load<Album>(id);
    return View(bookData);
    }
}
[HttpPost]
public ActionResult Delete(Album album)
{
    using (var session = documentStore.OpenSession())
    {
         session.Advanced.Defer(new DeleteCommandData { Key = "albums/" + album.Id });
         session.SaveChanges();
    return RedirectToAction("Index");
    }
}

Using the Defer command in the Advanced section of the session API, you can pass a DeleteCommandData instance which will instruct the session to delete the document upon the call to the SaveChanges method. This will ensure that the delete will be transactional because of its participation in the Unit Of Work of the session.



Click Here to download the sample application.

Note: Please resote all the packages used in the application.