ASP.NET MVC and MongoDb Part 2

In the former blogpost we've explored MongoDb and we've created a very basic MVC application with the norm.dll. We created a User and a Bug class, but we've only implemented some CR (and not UD) for the User class.
In this post I will explore how to deal with a one-to-many relationship in a document based database, i.e. a non relational database.
classdiagram

One user can submit more bugs, so there is a one to many relationship between the user and the bugs. But how to implement that in an app where there is no relational database and where there are no constraints?

This were the ViewModel pattern comes in.

Below I created a new class, the BugViewModel class, which is a combination of attributes or fields from the Bug and the User class:

namespace BugBase.ViewModels
{
    public class BugViewModel
    {
        public ObjectId Id { get; set; }
        public ObjectId UserId { get; set; }
        public string ShortDescription { get; set; }
        public string LongDescription { get; set; }
        public DateTime? Date { get; set; }
        public bool Status { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
    }
}

So, that's great. Thank you Framework! But however do I map those attributes to the User and Bug classes?
There is AutoMapper, an object to object mapper by Jimmy Bogard, available here. But I think Automapper is a bit complex to use. For simple scenario's, like BugBase, there is a solution in the ASP.NET MVC futures assembly. This assembly provides a static class, the ModelCopier, that can also use for copying values between View Model objects and Domain model objects. It's available here at Codeplex. The dll is called Microsoft.Web.Mvc.dll. Add a reference to it in BugBase and you're good to go.

The controller create method, would look like this:

[HttpPost]
 public ActionResult Create(BugViewModel bugviewmodel)
   {
       var bug = new Bug();
       ModelCopier.CopyModel(bugviewmodel, bug);

       using (var session = new MongoSession())
        {
         string username = bugviewmodel.UserName;
            var user = session.users
              .Where(u => u.UserName == username)
                  .FirstOrDefault();

                bug.User = user;
                session.Save(bug);                
         }
      return RedirectToAction("Index");
      }
 }

You see how easy it is to add a user to a bug using the ViewModel Pattern and copy the viewmodel to the original domain class.

Next time we'll spice up the userinterface and we'll add some jQuery and Ajax.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.