Using RavenDB in ASP.NET Applications

Introduction

Web applications commonly store data in some RDBMS, such as SQL Server. However, relational data is not the only type of data needed in an application. Your applications may need to handle data that doesn't fit into traditional row-column format. In such cases Document databases, such as RavenDB, come into the picture. To that end this article shows you how to work with RavenDB in an ASP.NET application.

NoSQL Initiative and RavenDB

Most of the applications developed today store data in one or another relational database, such as SQL Server. Any RDBMS expects that data to be stored is in a tabular format (Rows-Columns). However, in many cases the data to be stored may not be fit as relational data. Consider, for example, that you wish to store an arbitrary object in the data store. Another example can be arbitrary key-value kind of data.

Document databases essentially allow you to store data in "schema-less" fashion. That is you no longer define any fixed table structures in the data store. You store data as a document with a key and then later retrieve it using the same key. RavenDB is one such document database. RavenDB follows the NoSQL initiative, which doesn't require any SQL to access the data stored in the database. In other words you store data in RavenDB without defining any table schemas and access it without using any SQL statements. As far as accessing RavenDB from .NET applications is concerned, you use LINQ based syntax for data access.

RavenDB is designed for the Windows platform specifically geared towards .NET applications. It stores data in JSON format. The data can be accessed and manipulated using LINQ based syntax. Though there are multiple ways to deal with the data stored in RavenDB the easiest approach is to use the .NET Client API. Even the RavenDB server can be used in multiple ways but this article uses a standalone installation of the server for the sake of demonstrating its basic usage.

Installing the RavenDB Database Server

To install RavenDB on your machine you first need to download it by visiting the download section of the RavenDB website. Once you download and extract the RavenDB files on your machine, go to the Server folder and double click on the Raven.Server.exe. This will start the RavenDB console as shown below:

RavenDB Console
RavenDB Console

RavenDB also comes with a web interface. By default you can access the RavenDB web interface at http://localhost:8080/raven/studio.html. The following figure shows the web interface with some sample data already stored in the database.

RavenDB Web Interface
RavenDB Web Interface

Notice that the above figure shows Albums and Employees objects stored in the database. If you double click on any of the objects it will reveal its JSON representation as shown below:

JSON Representation
JSON Representation

Initially, when there is no data added to the data store, the same web interface also allows you to add sample data. For example, the Albums objects shown above are added through the web interface.

Keep the RavenDB server running and move on to the next step.

Installing the RavenDB Client API

The next step is to install .NET Client API for accessing the data stored in RavenDB. The easiest way to do so is to install an appropriate NuGet package. Create a new ASP.NET Web Application project in Visual Studio and then select the "Manage NuGet Packages" menu option from the Project menu. Then search for RavenDB.Client. Finally, select that package from the list and click on Install.

RavenDBDemo - Manage NuGet Packages
RavenDBDemo - Manage NuGet Packages

The complete list of available RavenDB NuGet packages is available here.

Now that you have set up the server as well as the .NET Client API you are ready to add, remove, and modify data in the RavenDB data store.

Developing a Sample Application

Now let's develop a web form as shown below that allows you to add, modify, and delete Employee objects to and from the RavenDB data store.

Web Form
Web Form

As you can guess from the figure the Employee object has three properties Id, FirstName, and LastName and is shown below:

namespace RavenDBDemo
{
    public class Employee
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }  
}

RavenDB offers three ways to handle the Id of a document. They are as follows:

  • Your object can have a property named Id. If you don't assign it explicitly to some value, RavenDB will generate a unique Id for you and will assign it to this property.
  • Your object can have a property named Id that you can set explicitly in your code. In this case RavenDB will use your Id value for the document but it is your responsibility to maintain the uniqueness of the Id values.
  • If your object doesn't have an Id property, RavenDB still generates and assigns a unique ID to it but you will need to figure out the Id assigned by RavenDB by making a separate Client API call.

In this example the Employee class has an Id property and you will assign it explicitly in the code.

Open the Global.asax file and add the following code to it.

using Raven.Client.Document;
using Raven.Client.Indexes;
using System.Reflection;
 public static DocumentStore Store;
 
protected void Application_Start(object sender, EventArgs e)
{
 Store = new DocumentStore { ConnectionStringName = "RavenDB" };
 Store.Initialize();
}

The above code first imports certain RavenDB Client API specific namespaces. It then creates a global variable of type DocumentStore. A document store is considered a resource intensive object and hence it is recommended to maintain only one instance of the DocumentStore object rather than creating it again and again. Inside the Application_Start event the DocumentStore is instantiated by passing the ConnectionStringName of RavenDB. The RavenDB connection string is stored in the web.config file as follows:

<connectionStrings>
  <add name="RavenDB" connectionString="Url=http://localhost:8080" />
</connectionStrings>

The Initialize() method of the DocumentStore object initializes the document store so that it is ready for further data access operations.

Next, go in the code behind of the default web form and add a helper method named FillList().

private void FillList()
{
    using (var session = Global.Store.OpenSession())
    {
        var employees = session.Query<Employee>()
        .ToList();
        DropDownList1.Items.Clear();
        for (int i = 0; i < employees.Count; i++)
        {
            ListItem item = new ListItem(employees[i].FirstName + " " + employees[i].LastName, employees[i].Id);
            DropDownList1.Items.Add(item);
        }
    }
}

As you can see from the above piece of code, the FillList() method gets hold of the global DocumentStore variable declared earlier inside the Global.asax file. It then calls the OpenSession() method on the DocumentStore to begin a new session of database operations. Notice how LINQ syntax is used to retrieve a list of Employee objects stored in the database (if any). A for loop then iterates through the Employees collection and fills the DropDownList with the employee name and Id.

The FillList() method is called from Page_Load so that when the page loads for the first time the DropDownList displays all the existing Employee objects.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        FillList();
    }
}

The code that adds a new Employee, modifies an existing Employee, and removes an existing Employee is located in the Click event handler of Add, Update, and Delete buttons respectively. The following code shows how a new Employee can be added to the data store.

protected void Button1_Click(object sender, EventArgs e)
{
    Employee emp = new Employee();
    emp.Id = TextBox1.Text;
    emp.FirstName = TextBox2.Text;
    emp.LastName= TextBox3.Text;
 
    using (var session = Global.Store.OpenSession())
    {
        session.Store(emp);
        session.SaveChanges();
        FillList();
    }
}

The code essentially constructs a new Employee object by grabbing values entered in various textboxes. The Store() method of the RavenDB session object adds the specified Employee object. The SaveChanges() method actually saves the newly added object to the database.

The Update and Delete operations are quite similar and involve finding a particular Employee to be updated or deleted respectively. The following code shows how an existing Employee object can be Deleted.

protected void Button4_Click(object sender, EventArgs e)
{
    using (var session = Global.Store.OpenSession())
    {
        var emp = session.Query<Employee>()
        .Where(x => x.Id == DropDownList1.SelectedValue)
        .SingleOrDefault();
 
        session.Delete(emp);
        session.SaveChanges();
        FillList();
    }
}

Notice how the LINQ where condition is specified to fetch only a single Employee object. The Delete() and SaveChanges() method calls then delete the Employee object.

That's it! Run the web form and try adding, removing, and updating Employee objects. You can also check them via the RavenDB web interface discussed earlier.

Summary

RavenDB is a NoSQL document database that stores data in JSON format. The RavenDB server has a web interface that can be used to examine data. RavenDB .NET Client API allows you to interact with the data store from your ASP.NET application. Using RavenDB you can easily store data that can't be categorized as relational data yet requires data manipulation operations such as add, update and delete. This article introduced you to RavenDB and its basic data manipulation operations. You can explore more features of RavenDB by visiting the documentation section of the RavenDB website.



Related Articles

Downloads

Comments

  • clarisonic pro with the body whisk is sterling as regards me

    Posted by iouwanzi on 06/06/2013 02:14am

    [url=http://www.australiaclarisonic.com/clarisonic-mia]clarisonic mia[/url] Victoria Secret 2012, la dernière conférence de maillots de bain sur la belle Miranda Kerr trésor et sexy top model Candice Swanepoel lors de la sélection se tailler un style de grands ghd lisseur cheveux de milliers de féminité sexy. Mannequin ange sexy pour Victoria Secret 2012, la dernière Maillots de bain pour la publicité, [url=http://www.miaclarisonicaustralia.org/clarisonic-classic]clarisonic classic[/url] Tout simplement parce que mon conjoint et j’ai affirmé au départ, j’ai acquis mon personnel Lisseur à votre maison dès le début, et même il effectue cependant.L’application peut être alors certainement les données de la catégorie du supplément.Tout ce que j’ai tirer du plaisir de la quasi-totalité est en fait d’une seule ligne sur ma chevelure, certaines personnes sont même encore étant le beau mouvement. Mis à part que l’utilisation de la marchandise dans la variété, on défendre cheveux agréable grâce à la chaleur du fer et ils sont généralement bien brillantes. Nous nous rendons compte que quand je ne résiderait pas non ce fer ! [url=http://www.miaclarisonicaustralia.org/]clarisonic mia online[/url] Les producteurs primaires suivantes commencé pour sa bonne qualité merveilleuse de votre sèche-cheveux et fer à lisser est aujourd’hui célèbre également la distinction entre les femmes qui parfois vous avez besoin pour redresser votre chevelure afin d’éliminer ces types de problèmes ghd fer luxe Violet, à son tour, n’est pas un peu ne serait tout simplement pas seulement en possession du logiciel. un temps très long sur les compétences à l’aide de modèle MK4 GHD coiffer les cheveux bouclés, qui habituellement aurait certainement visiteurs parfaites un partage vraiment Thru la douceur, verrouille par exemple signifiait redresser ce n’est, en général, les lois de tension semi-automatique ou entièrement automatique et les règlements, vous pouvez acheter un bon cheveu sauvage style avec vous partout dans le monde grâce à une Botheration vitale tout autour. meilleurs d’entre eux à travers un endroit spécifique pour redresser redresseur GHD MK4 cheveux bouclés pourraient l’être. problème en effet, le fait qui se produit à l’aide d’un opérateur capable dvd, plus de points, le type choisi des méthodes simples pour vous aider à contrôler l’application correcte et

    Reply
  • fitflop mcbvgz

    Posted by naksvqob on 05/20/2013 01:21am

    ukfitflop.webeden.co.uk/ Your Sundowner is an traditional isle terrace providing vintage Jamaican foodstuff having an Oriental highlight. White-glove services found right here. Kimonos offers Teppanyaki dining both tasty and also interesting, together with culinary chefs successful inside their culinary arts along with showman capabilities, providing tantalizing shrimp, seared beef and also tender hen, flame-grilled ahead of your vision. Without shoes through the Sea is another white-glove knowledge difficult through the marine and directly on the seashore. [url=http://fitflop-shoes.webs.com/]fitflop[/url] In addition, these are comfortable with solid mid-foot ( arch ) help, lots of padding and also breath-ability in the toes and fingers. The only real negatives include the not enough just about any remarkable brand-new hyped up publicity stunt -- which means you can rest easy knowing that each of the World Vegases features are usually screened and also ... look at this assessment.Planet Castro Skate boarding Slipper ReviewGlobe Castros are similar to excellent slip-ons which simply are skatable. They are usually comfortable and soft, warm, and also wear along with off of quickly. Flip them over, and you can notice they've got a tough, grippy lone which means it is possible to skate board along with your World Castros upon. [url=http://ukfitflop.webeden.co.uk/]fitflops[/url] Girls Dress Shoes * Top choices within Sweet Sports shoes with regard to GirlsFinding dress shoes for women throughout quality college is fairly simple, yet finding a couple which she's going to like just as much as you do is a touch a lot more challenging. Here are a few you will equally similar to.How you can Go shopping for Could Footwear an advanced ManLearn how you can determine the girl personalized style along with shop for females footwear, and you might only unlock the key to be able to your ex cardiovascular.Gents Dress Shoes - Top Picks with regard to MenFrom monk connectors to be able to wing-tips; oxfords for you to loafers; as well as basic dark-colored in order to deep red; a list features a costume sneaker for every form of man. fitflop sale In high price items, rooms and also rooms along with assistant service and also other services include a amount of luxury to the expertise. Almost all suites have a very Spa plus a stored minibar. The accommodation is all around a regular plaza edged by simply designed courtyards. Its restaurants behaves Italian, Caribbean sea, Asian, Tex-Mex, smorgasboard, and also bakery fare. Sandals Whitehouse All-Inclusive includes four pools; one of which is the largest inside Barbados. New sandals Whitehouse All-Inclusive also has a character walk, health spa facilities, along with a health and fitness center.

    Reply
  • Coast Sale exczhkyw

    Posted by qirffoqhx on 05/07/2013 01:50pm

    [url=http://burberrybags.webeden.co.uk/]burberry bags[/url] Functioning clothing and also clothing that do not coast british particularly will safeguard the medical and also safety regarding employees. Coast Outlet Shopbop Launches Workwear Specialist. -- Online with free streaming LibraryNEW You are able to Nyc, state, Usa StatesNew You are able to,Center Ocean state of america. It can be outlined through Vermont, Boston, Ct, and the Atlantic (At the), Nj as well as Missouri (Ersus), Ponds Erie along with New york along with the Canada province regarding , Jan 25, The coming year /PRNewswire/ --Shopbop.com, an established resource regarding laid-back and festiveessentials, launches Workwear Noun A single. [url=http://coastsale.webeden.co.uk/]coastsale.webeden.co.uk/[/url] There were 79 a lot within the auction; 55 byCatherine Master, seacoast sale 14 Edelsteins, five Oldfields, a few from Arbeid, twoeach from your Emanuels, Zandra Rhodes and Bellville-Sassoon/LorcanMullany. Then one every coming from Hachi, Yuki, Gina Fratini along with ChristinaStambol ian. Your Gina Fratini white sari-style outfit, created whilst shewas operating from Norman Hartnell, travelled with regard to lbs Fifty one,128; Hachi'swhite one-shouldered dress fetched pounds Forty five,173; and Stambolian'swicked minor african american Divorce proceedings Outfit gone pertaining to weight 46,511. However Edelstein's night time velvety shoreline Travolta outfit reach the particular lottery jackpot, raisingpounds 133,835. Since the designer said: "I are aware that the actual Princessfavoured the particular dark blue purple velvet clothe themselves in the actual purchase. burberry bags

    Reply
  • Jordan shoes mentioned Gene to go for the variety, a disunion of Nike

    Posted by TaddyGaffic on 04/22/2013 08:55pm

    In focus groups conducted at 80 community-based organizations around the country, Motivational Educational Entertainment of Philadelphia [url=http://markwarren.org.uk/property-waet.cfm]air max 90[/url] identified disturbing trends among youths ages 16 to 20. The "Just Say No" message of abstinence-only campaigns has been lost on this group of young people, who grew up during an era when the hip-hop sensibility of getting cash and clothes did not incorporate values of conscientious sexual behavior or social responsibility. Rappers who mingle [url=http://northernroofing.co.uk/roofins.cfm]nike free run 3[/url] with glamorous-looking half-naked women rarely mention contraception while they're listing the number of compromising sexual situations they've been in lately. There are number of good brands in the market like Adidas, Nike, Reebok, Asics, Brooks, Puma etc. Most of these brands have shoes tailored for professional and amateur tennis players. New advanced technologies have made these shoes more player-friendly. After that, I eventually like to try to get down to the 150-160 range. I not entirely sure if that a healthy number for a gal my height or not, and I haven looked into it. But, I know that when I was 180 I still didn feel that [url=http://markwarren.org.uk/property-waet.cfm]air max 90[/url] fit, so I think an extra 20 or so will help with that.. Lotto sneakers selling price are generally liable along with using the form of sneakers you choose on. Your Lotto sneakers established fact because of their style along with good quality plus the create. That they create sneakers coming from all varieties much like the loafers,Puma II Shoes, new sandals, sneakers along with task tennis shoes or anything else

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: May 7, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT This eSeminar will explore three popular games engines and how they empower developers to create exciting, graphically rich, and high-performance games for Android® on Intel® Architecture. Join us for a deep dive as experts describe the features, tools, and common challenges using Marmalade, App Game Kit, and Havok game engines, as well as a discussion of the pros and cons of each engine and how they fit into your development …

  • On-demand Event Event Date: April 22, 2014 Database professionals -- whether developers or DBAs -- can often save valuable time by learning to get the most from their new or existing productivity tools. Whether you're responsible for managing database projects, performing database health checks and reporting, analyzing code, or measuring software engineering metrics, it's likely you're not taking advantage of some of the lesser-known features of Toad from Dell. Attend this eSeminar with Dell Software's …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds