NoSQL using MongoDB, NoRM, and ASP.NET MVC

Original author: Shiju Varghese
  • Transfer


In this article, I would like to tell how to work with NoSQL and the document-oriented database MongoDB, NoRM and ASP.NET MVC 2.

NoSQL and Document Oriented Database


This year, active movements towards NoSQL are especially noticeable and people are constantly discussing the use of document-oriented databases along with web applications. According to Wikipedia, “NoSQL is a movement promoting a free class of non-relational data warehouses that interrupted the long history of relational databases. Storage data may not require fixed schemas for tables, most often they avoid join operations and usually have horizontal scaling. Teachers often refer to such databases as structured repositories.

Document-oriented databases are schema-independent, so you can focus on the problem domain and not worry about updating the schema during domain extensions, which allows you to use a real domain-oriented approach to development. One of the main problem areas in relational databases is the synchronization of the database schema with domain entities when the domain itself develops. At the moment, there are a huge number of implementations of the NoSQL approach, but CouchDB and MongoDB attracted my attention more. Watching the development of both databases, I found that CouchDB is not able to perform dynamic queries, so I later adopted MongoDB. There are many drivers for .NET for this database.

Mongodb


MongoDB is an open-source, extensible, high-performance, schema-free, document-oriented database written in C ++. Developed since October 2007 by 10gen. MonoDB stores all your data in binary JSON (BSON) format. MongoDB is attracting more attention and, as you can see, has become widespread in real life.

NoRM - C # driver for MongoDB


NoRM is a C # driver for MongoDB that supports LINQ. NoRM project is available on Github .

ASP.NET MVC Demo


I will show a simple example using MongoDB, NoRM and ASP.NET MVC. To work with MongoDB and NoRM, follow these steps:
  1. Install MongoDB for 32bit or 64bit version. The archives contain mongodb.exe for starting the server and mongo.exe for the client.
  2. Download NoRM Driver for MongoDB
  3. Create a directory named “C: \ data \ db”. This is the standard location for MongoDB databases.
  4. Launch MongoDB server C: \ Mongo \ bin \ mongod.exe.

Now, I'm going to demonstrate how to create an ASP.NET MVC application using MongoDB and NoRM.

Let's write a domain class.
public class Category
{     
  [MongoIdentifier]
  public ObjectId Id { get; set; }

  [Required(ErrorMessage = "Name Required")]
  [StringLength(25, ErrorMessage = "Must be less than 25 characters")]
  public string Name { get; set;}

  public string Description { get; set; }
}

ObjectId is the NoRM type that represents the MongoDB ObjectId. NoRM will automatically update Id because it is equipped with the MongoIdentifier attribute. The next step is to create the MongoSession class. It will carry out any interaction with MongoDB.
internal class MongoSession : IDisposable
{
  private readonly MongoQueryProvider provider;

  public MongoSession()
  {
    this.provider = new MongoQueryProvider("Expense");
  }

  public IQueryable Queryable
  {
    get { return new MongoQuery(this.provider); }
  }

  public MongoQueryProvider Provider
  {
    get { return this.provider; }
  }

  public void Add(T item) where T : class, new()
  {
    this.provider.DB.GetCollection().Insert(item);
  }

  public void Dispose()
  {
    this.provider.Server.Dispose();
  }

  public void Delete(T item) where T : class, new()
  {
    this.provider.DB.GetCollection().Delete(item);
  }

  public void Drop()
  {
    this.provider.DB.DropCollection(typeof(T).Name);
  }

  public void Save(T item) where T : class,new()
  {
    this.provider.DB.GetCollection().Save(item);     
  }
}

The MongoSession constructor will create an instance of MongoQueryProvider that supports LINQ expressions, and also create a database called “Expense”. If the database with the same name is already present, then it will use the existing one. The Save method can be used for both Insert and Update operations. If the object is new, a new record will be created, otherwise the document data with the transmitted ObjectId will be updated.

Let's create an ASP.NET MVC controller and action methods to handle the CRUD script for the Category domain class.
public class CategoryController : Controller
{

//Index – Получаем список категорий
public ActionResult Index()
{
  using (var session = new MongoSession())
  {
    var categories = session.Queryable.AsEnumerable();
    return View(categories);
  }
}

//Редактируем единственную категорию
[HttpGet]
public ActionResult Edit(ObjectId id)
{
  using (var session = new MongoSession())
  {
    var category = session.Queryable
       .Where(c => c.Id == id)
       .FirstOrDefault();

    return View("Save",category);
  }
}

// GET: /Category/Create
[HttpGet]
public ActionResult Create()
{
  var category = new Category();
  return View("Save", category);
}

//Добавляем или изменяем категорию
[HttpPost]
public ActionResult Save(Category category)
{
  if (!ModelState.IsValid)
  {
    return View("Save", category);
  }
  using (var session = new MongoSession())
  {
    session.Save(category);
    return RedirectToAction("Index");
  }
}

//Удаляем категорию
[HttpPost]
public ActionResult Delete(ObjectId Id)
{
  using (var session = new MongoSession())
  {
    var category = session.Queryable
       .Where(c => c.Id == Id)
       .FirstOrDefault();
    session.Delete(category);
    var categories = session.Queryable.AsEnumerable();
    return PartialView("CategoryList", categories);
  }
}   
}

As you can see, you can easily work with MongoDB using NoRM in ASP.NET MVC applications. I created a repository on CodePlex where you can download the source code for this ASP.NET MVC application.

Also popular now: