Wednesday, March 27, 2013

RavenDB with MVC 4

I've decided to use RavenDB for a project that I'm working on. I've been researching a number of database options for a site which could eventually have pretty rigorous traffic load. Though I really like MS SQL as a traditional relational DB I've seen it, when coupled with naive EF use, become a horrible drag on performance.

So far I'm pretty impressed. It is very nice not to have to setup and maintain a dedicated ORM just to translate from the real world of objects into a flattened and normalized set of tables. I've created a set of "POCO" database classes in my BI/Services project (though for a larger project I'd probably simply have a dedicated database project). For the classes that will be the document that is stored I've added a string property to receive the document ID. For those that I'll explicitly define the key I simply added a method to the DB class "GetKey()" - in the example below the key is "UserProfile/curtis.forrester".

public DBModels.UserProfile GetUserProfile(string username)
{
    using (IDocumentSession raven = Store.OpenSession())
    {
        UserProfile user = raven.Load<UserProfile>(UserProfile.GetKey(username));
        return user;
    }
}

public void StoreUserProfile(UserProfile profile)
{
    using (IDocumentSession raven = Store.OpenSession())
    {
        raven.Store(profile, profile.GetKey());
        raven.SaveChanges();
    }
}
This is all that is necessary to store and load a UserProfile document. Since the data is stored as JSON I also modified the class and had no issues at all. I added some properties, loaded the UserProfile, set the new properties and stored the document and the updated "record" now reflected the new version.

The flexibility that Raven provides to generate keys for new documents is fantastic. From fully letting the server handle it to providing a method for you to register a custom handler is great.

Like all databases some knowledge and experience will be required to make sure that performance is up to par. I did some initial testing where I stored a bunch of documents that had collections and then loaded them. I found that loading each individual document was much slower than using their bulk loading approach. I found that the sweet spot was to load between 25 and 50 documents. When I increased the number to 500 or 1000 it was as slow as loading each one-by-one.

No comments: