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 _users;

  public HomeController()
  {
    MongoDatabase database = MongoDatabase.Create("mongodb://localhost:27017/TestMvc3MongoDB");
    _users = database.GetCollection("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)                                                    
    
}

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

,

2 responses to “ASP.NET MVC 3 & MongoDB: CRUD operations in NoSQL database using FluentMongo”

  1. Nice post,helpful for the Enthusiast to try to get the best of two world. I was trying to do the same thing last night.

    The model binding for object Id was a problem, I’ll try to add another string id.

    Another finding is the 1.5driver supports linq, so I didn’t use fluent linq.

    One problem with this version driver is, it seems having trouble to convert object Id to string, despite it claims resolved here https://jira.mongodb.org/browse/CSHARP-496?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel#issue-tabs.

    I used mvc4 rc, it works too. Similar the way it works in 3.

    Overall, it’s a good impression to work with mongodb in asp.net mvc. Hope this combination can go to the next level.

  2. In Small words we can say that very helpfull and great post and easy to understand.
    Thanks
    Mukesh kaushik

Leave a Reply

Your email address will not be published. Required fields are marked *