📜 ⬆️ ⬇️

NoSQL using MongoDB, NoRM and ASP.NET MVC



In this article, I would like to tell you 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 in the direction of NoSQL are especially noticeable, and people are constantly discussing the use of document-oriented databases with web applications. According to Wikipedia, “NoSQL is a movement promoting a free class of non-relational data warehouses that has interrupted a long history of relational databases. Storage data may not require fixed schemas for tables, most often avoid join-operations and usually have horizontal scaling. Teachers often refer to such databases as structured vaults.
')
Document-oriented databases are not dependent on schemas, 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 during development. One of the main problem areas in relational databases is the synchronization of the database schema with the 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. Observing the development of both databases, I found that CouchDB is not able to perform dynamic queries, so I later adopted MongoDB. For this database there are many drivers for .NET.

MongoDB


MongoDB is an open source, scalable, 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 attracts more and more attention and, as you can see, it 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 .

Demonstration of working with ASP.NET MVC


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. Archives contain mongodb.exe to start the server and mongo.exe for the client.
  2. Download the NoRM driver for MongoDB
  3. Create a directory with the name “C: \ data \ db”. This is the standard location of the MongoDB databases.
  4. Start the 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 a NoRM type that represents MongoDB ObjectId. NoRM will automatically update the Id because it is equipped with the MongoIdentifier attribute. The next step is to create the MongoSession class. He will perform any interaction with MongoDB.
internal class MongoSession<tentity> : IDisposable
{
private readonly MongoQueryProvider provider;

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

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

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

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

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

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

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

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

The MongoSession constructor creates an instance of MongoQueryProvider that supports LINQ expressions, and also creates a database called “Expense”. If the base with the same name is already present, 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 will be updated with the passed ObjectId.

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<category>())
{
var categories = session.Queryable.AsEnumerable<category>();
return View(categories);
}
}

//
[HttpGet]
public ActionResult Edit(ObjectId id)
{
using ( var session = new MongoSession<category>())
{
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<category>())
{
session.Save(category);
return RedirectToAction("Index");
}
}

//
[HttpPost]
public ActionResult Delete(ObjectId Id)
{
using ( var session = new MongoSession<category>())
{
var category = session.Queryable
.Where(c => c.Id == Id)
.FirstOrDefault();
session.Delete(category);
var categories = session.Queryable.AsEnumerable<category>();
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 of this ASP.NET MVC application.

Source: https://habr.com/ru/post/93598/


All Articles