As I wrote in my last post from (shame on me!) last year, I don’t like to focus on databases that much. I’d rather spend my time with domain objects instead of thinking about inner joins, cross outer joins, views and stored procedures. Why? Because I always had to do things twice: designing a domain model and then designing the database for persistence. Or, even work with an existing database! And those two often clashed (the famous object-relational impedance mismatch).
Object Relational Mapping (ORM) like SubSonic and nHibernate are great in this respect but the mapping can be somewhat complex (which might be not true anymore for the most recent version of nHibernate which I haven’t checked out yet). Then Microsoft introduced Linq 2 SQL which is great to quickly generate classes from a database (not the other way round unfortunately). But rumour has it Microsoft is turning Linq 2 SQL into legacy.
In “The end of SQL and relational databases?” the author states “With the growing trend of ORMs (Object Relational Mapping), some software developers are saying that SQL is becoming less relevant.” Now whether that statement is true or false, it sure is very interesting to investigate some Object Databases, the alternative method for data persistance.
Download MongoDB (Windows 32 bits for me) and extract it to c:\data\db (this is the default). You can start the database with mongod.exe
Next, download these 2 dll’s to talk to MongoDB from C#.
Fire up Visual Studio and create a new C# console application. Add a reference to those two dll’s like this:
And finally some code:
static void Main(string args)
//create a new Mongo instance
var mongo = new Mongo();
//connect to it
//connect to DB (or create new if it not exists)
var db = mongo.getDB("Frots");
//connect to the collection (like a table)
var frotten = db.GetCollection("frotten");
//create a document (like a record)
var newFrot = new Document();
newFrot["titel"] = "nosql";
newFrot["tekst"] = "Frotten zonder RDBMS is goed";
//find a document
var zoekFrot = new Document();
zoekFrot["titel"] = "nosql";
var gezochteFrot = frotten.FindOne(zoekFrot);
This results in the following:
While this may not look spectacular, it could be if I would have created a fancier app. But the simplicity is overwhelming. I didn’t need to create tables or schemas or setup primary keys. It just worked like that.
So, I think these NoSQL databases could be a hit for .NET.
I am not saying RMDB’s are bad though. I just think Object Databases are a great and simple way to store your objects.
And a very elegant way, at that.