ASP.NET MVC 3 & MongoDB: CRUD operations in NoSQL database using FluentMongo

This blog post shows how to use the open-source NoSQL database MongoDB in an ASP.NET MVC 3 web application. The showcase web application uses FluentMongo that adds LINQ-support for the 10gen MongoDB C# driver. Summarized the application demonstrates how to perform the basic CRUD (create, read, update and delete) database operations.

Before running the example web application, please make sure that a MongoDB server is up and running on your machine (see MongoDB Quickstart for Windows).

We start with an empty ASP.NET MVC 3 web application and use the NuGet package manager to install the following packages:

  • FluentMongo (installs also the dependent MongoDB C# driver)
  • MvcContrib (used in this example to easily create HTML grids)

After including the required NuGet packages we add our User model (Models/User.cs):

public class User
{
  [BsonId]
  public ObjectId ObjectId;
 
  [ScaffoldColumn(false)]
  public String Id {
    get { return ObjectId.ToString(); }
    set { ObjectId = new ObjectId(value); }
  }
 
  [DisplayName("First Name")]
  [Required]
  public String FirstName { get; set; }
 
  [DisplayName("Last Name")]
  [Required]
  public String LastName { get; set; }
}

Since ASP.NET MVC 3 does not support binding MongoDB’s ObjectId (used by the database to identify the records) the User model contains two id properties:

  • ObjectId: The (BSON) id used by MongoDB to identify the records in the database
  • Id: The (string) id used by the ASP.NET MVC 3 application in GET and POST request data to identify the records

The getter and setter in the Id attribute “synchronizes” the string and the BSON value. In a real world project one should solve this problem in a more generic way, e.g. by implementing a custom ModelBinder or by separating database entities from MVC models.

Next, we implement the HomeController (Controllers/HomeController.cs) as follows:

public class HomeController : Controller
{
  private MongoCollection<User> _users;
 
  public HomeController()
  {
    MongoDatabase database = MongoDatabase.Create("mongodb://localhost:27017/TestMvc3MongoDB");
    _users = database.GetCollection<User>("Users");
  }
 
  [HttpGet]
  public ActionResult Delete(String id)
  {
    var user = _users.AsQueryable().FirstOrDefault(e => e.Id == id);
    if (user != null) _users.Remove(Query.EQ("_id", new ObjectId(id)));
    return RedirectToAction("Index");
  }
 
  [HttpGet]
  public ActionResult Edit(String id)
  {
    var user = _users.AsQueryable().FirstOrDefault(e => e.Id == id) ?? new User();
    return View(user);
  }
 
  [HttpPost]
  public ActionResult Edit(User user)
  {
    if (ModelState.IsValid)
    {
      _users.Save(user);
      return RedirectToAction("Index");
    }
    return View(user);
  }
 
  public ActionResult Index()
  {
    return View(_users.AsQueryable());
  }
}

In a last step we add the view that shows all records (Views/Home/Index.cshtml):

@Html.Grid(Model).Columns(column => {
    column.For(x => x.Id).Named("Person ID");
    column.For(x => x.FirstName).Named("First Name");
    column.For(x => x.LastName).Named("Last Name");
    column.For(x => Html.ActionLink("Edit", "Edit", new { id = x.Id }));
    column.For(x => Html.ActionLink("Delete", "Delete", new { id = x.Id }));
})
 
@Html.ActionLink("Create Record", "Edit")

and the view that shows the form to edit and create records (Views/Home/Edit.cshtml):

@using (Html.BeginForm())
{
    @Html.Hidden("Id", Model.Id);
    @Html.EditorForModel(Model)
    <input type="submit" value="Submit"/>
}

You can download the Visual Studio 2010 project containing all the source code here.