In my previous post in this series on NoSQL Databases, I showed how RavenDB embedded could be added to an existing ASP.NET MVC 3 application using NuGet and how it can be configured to use a folder in the App_Data folder. 

In this blog I will add the code needed for my TaskController class to use RavenDB to store its data.

Everything in RavenDB goes through an instance of IDocumentStore.  There are two classes in the RavenDB API which implement this interface DocumentStore and EmbeddedDocumentStore.  We will be using the latter.

We can create a RavenDocumentStore class which is like the DataContext or DbContext classes in Entity Framework.

Listing 1: The RavenDocumentStore Class
public class RavenDocumentStore
{
    private static IDocumentStore instance;

    public static IDocumentStore Instance
    {
        get
        {
            if (instance == null)
                throw new InvalidOperationException("…");
            return instance;
        }
    }

    public static IDocumentStore Initialize()
    {
        instance = new EmbeddableDocumentStore
                        {
                            ConnectionStringName = "RavenDB"
                        };
        instance.Conventions.IdentityPartsSeparator = "-";
        instance.Initialize();
        return instance;
    }
}
 

The static property Instance ensures that we only have one instance of the DocumentStore, and the Initialize method can be called in Application_Start.  We could have created the instance inside the Instance getter, but that would not be thread-safe.

Listing 2: The Application Start method
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RavenDocumentStore.Initialize();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}
 

We are going to need an IDocumentSession to do the work.  We could create a new IDocumentSession instance at the beginning of each Action method and then dispose of it at the end of each method.  But MVC has two very convenient hooks to do this – OnActionExecuting and OnActionExecuted.  These methods are executed before and after each action method, so we will create a new IDocumentSession in OnActionExecuting and dispose of it in On ActionExecuted.  To do this we will create  a BaseRavenController class to act as a base class for our TaskController (Listing 3).

Listing 3: The BasenRavenController class
public class BaseRavenController : Controller
{
    public IDocumentSession RavenSession { get; set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        RavenSession = RavenDocumentStore.Instance.OpenSession();
        base.OnActionExecuting(filterContext);
    }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (RavenSession != null)
        {
            RavenSession.SaveChanges();
            RavenSession.Dispose();
        }
        base.OnActionExecuted(filterContext);
    }
}

Finally we can then modify each action method to use the RavenSession instead of the Entity Framework DbContext.  As an example the Index action (Listing 4) and the Edit actions (Listing 5) are shown.

Listing 4: The Index Action method
public ViewResult Index()
{
    var tasks = RavenSession.Query<Task>().ToList();
    return View(tasks);
}

 

Listing 5: The Edit Action methods
public ActionResult Edit(string id)
{
    Task task = RavenSession.Load<Task>(id);
    return View(task);
}

[HttpPost]
public ActionResult Edit(Task task)
{
    if (ModelState.IsValid)
    {
        RavenSession.Store(task);
        return RedirectToAction("Index");
    }
    return View(task);
}

That is basically it – although there is one last change that needs to be made.  RavenDB uses a “key” to identify each document.  By default, just like an Identity column in SQL Server, RavenDB will generate this key automatically – the default behaviour being to create a key of the form “tasks/1” – i.e. the plural of the object’s name followed by the default “/” separator and a hilo generated integer. 

The default separator can be changed and we did that in Listing 1 by setting the IdentityPartsSeparator  to a “-“, so that we didn’t interfere with the Url separator in our routes.  And since we now have a string “key” the Id property of our Task object (and all the Action method parameters) can be changed to a string.

Figure 1 and Figure 2 show the Tasks Application running in List and Edit mode.

Figure 1: The MyTasks MVC Application in List (Index) view
image

 

Figure 2: The MyTasks MVC Application in Edit view
image

So that’s it – its not very hard at all to start working with RavenDB.  The only challenge so far being that I cannot look into the Data Store in the same way that I can with the SQL Server tools in Visual Studio or SQL Management Studio.

However, this is not the end of this series of Blogs.  I will continue to explore NoSQL databases, in particular RavenDB.


Posted in: Data  Tags: , , ,

Comments


November 26. 2011 15:04
security toronto
Hey , thank you for bringing up your ideas on this website. I wound up inside your blog right after researching physical fitness connected issues on Yahoo… guess I lost track of what I had been performing! Anyway I’ll be back once again within the long run to check out your blog posts down the road.


December 5. 2011 18:15
 cholesterol
The blood-pressure reduction does not seem to depend on the frequency or intensity of aerobic exercise or on the type of exercise.


December 11. 2011 12:03
womens fitness
Great job on featuring actually likely one of one of the critical advanced blogs Ive arrive across in a while! Its basically wonderful how a lot you’ll have the ability to consider away from a factor mainly merely due to how aesthetically striking it is. Youve place collectively an amazing blog site space -great graphics, films, layout. That is certainly a must-see web site!


December 14. 2011 00:05
Toronto condos
I have witnessed that wise real estate agents everywhere you go are starting to warm up to FSBO Promoting. They are realizing that it\'s not only placing a sign in the front property. It\'s really about building interactions with these vendors who someday will become customers. So, when you give your time and effort to serving these retailers go it alone - the \"Law regarding Reciprocity\" kicks in. Interesting blog post.


December 17. 2011 06:05
apartments toronto
Hey , I’ve just started my own online presence for my business, but there are some great ideas in the list that I really could do and hadn’t thought of at all. I would like to add this to my real estate FB , not sure how to do it yet, but I will figure it out somehow.


December 18. 2011 11:01
Michael Nicklaus
Hey , I really hope the real estate market is a great deal better in 2012. I hope you as well as your loved ones enjoy a safe and Happy Holiday and prosperous New Year and may 2012 to be a terrific year for you.

 Search Blog

 Calendar

«  February 2012  »
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011
View posts in large calendar

 Tags

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 Thoughts from the Wet Coast