Porting MVC Music Store to RavenMigrations

time to read 5 min | 807 words

On my last post, I mention that we need to add a CountSold property to all the albums, in most SQL system, something like that can be pretty painful. The syntax for adding a new column is easy, but actually getting it done, and deployed, and versioned, is pretty hard. With Raven, if you add a new property, it will automatically be added to your document when you next save it. There is no action required on your part. The same, by the way, would happen when you remove a property. Raven will clean it up after you.

The question is what happens when we want to set that value to something, not just to the default value? We need to provide that logic somehow, and here is a simple way of doing so;

using (var documentStore = new DocumentStore { Url = "http://localhost:8080" })
{
    documentStore.Initialise();
    using (var session = documentStore.OpenSession())
    {
        IDictionary<string,int> albumToSoldCount = new Dictionary<string, int>();
        int count = 0;

        do
        {
            var results = session.Query<SoldAlbum>("SoldAlbums")
                .Take(128)
                .Skip(count)
                .ToArray();

            if (results.Length == 0)
                break;
            count += results.Length;
            foreach (var soldAlbum in results)
            {
                albumToSoldCount[soldAlbum.Album] = soldAlbum.Quantity;
            }
        } while (true);

        count = 0;
        do
        {
            var albums = session.Query<Album>()
                .Skip(count)
                .Take(128)
                .ToArray();
            if (albums.Length == 0)
                break;

            foreach (var album in albums)
            {
                int value;
                albumToSoldCount.TryGetValue(album.Id, out value);

                album.CountSold = value;
            }

            count += albums.Length;

            session.SaveChanges();
            session.Clear();
        } while (true);
    }
}

To those of you who haven’t bother to read the code, this is reading the index that we previously created and remembering its value. Then we start reading batches of albums and update their counts. All in all, it is quite simple.

An additional nice property of this script is that you can run it is safe to run it multiple times.

More posts in "Porting MVC Music Store to Raven" series:

  1. (31 May 2010) StoreManagerController, part 2
  2. (29 May 2010) StoreManagerController
  3. (28 May 2010) Porting the checkout process
  4. (25 May 2010) StoreController
  5. (24 May 2010) Advanced Migrations
  6. (23 May 2010) Migrations
  7. (22 May 2010) Porting the HomeController, the Right Way
  8. (21 May 2010) Porting the HomeController, the map/reduce way
  9. (20 May 2010) Data migration
  10. (19 May 2010) Setting up the application
  11. (18 May 2010) The data model