You are currently browsing legacy 2.5 version of documentation. Click here to switch to the newest 4.2 version.

We can help you with migration to the latest RavenDB

Contact Us Now
see on GitHub

Creating ASP.NET MVC 4 Project with RavenDB

In this section we will go over the steps to creating you own ASP.NET MVC4 Application.

Prerequisites

1) Make sure you have the Microsoft ASP.NET MVC 4 installed.
2) You have installed NuGet package manager 3) You are running Visual Studio 2010 or greater

Step by Step Instructions

1) Open the Micrsooft Visual Studio IDE. Create a new "ASP.NET MVC 4 Web Application" project.
2) As Project template select "Basic".
3) Add the NuGet Package named "RavenDB Client".
4) Create the following controller:

public abstract class RavenController : Controller
{
	public static IDocumentStore DocumentStore
	{
		get { return DocumentStoreHolder.Store; }
	}

	public IDocumentSession RavenSession { get; protected set; }

	protected override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		RavenSession = DocumentStoreHolder.Store.OpenSession();
	}

	protected override void OnActionExecuted(ActionExecutedContext filterContext)
	{
		if (filterContext.IsChildAction)
			return;

		using (RavenSession)
		{
			if (filterContext.Exception != null)
				return;

			if (RavenSession != null)
				RavenSession.SaveChanges();
		}

		TaskExecutor.StartExecuting();
	}

	protected HttpStatusCodeResult HttpNotModified()
	{
		return new HttpStatusCodeResult(304);
	}

	protected ActionResult Xml(XDocument xml, string etag)
	{
		return new XmlResult(xml, etag);
	}

	protected new JsonResult Json(object data)
	{
		return base.Json(data, JsonRequestBehavior.AllowGet);
	}
}

5) From now on, write you application as you would normally, but make any controller that needs to talk to RavenDB inherit from RavenController.

Example of a controller:

public class HomeController : RavenController
{
	//
	// GET: /Home/

	public ActionResult Index()
	{
		var items = RavenSession.Query<SampleData>().ToList();
		return View("Index", items);
	}

	public ActionResult Add(string name)
	{
		var sampleData = new SampleData { CreatedAt = SystemTime.UtcNow, Name = name };
		RavenSession.Store(sampleData);
		return RedirectToAction("Edit", new { id = sampleData.Id });
	}

	public ActionResult Edit(int id)
	{
		var sampleData = RavenSession.Load<SampleData>(id);
		return View("Index", new List<SampleData> { sampleData });
	}
}