Wednesday, April 11, 2012

The Model

The next step was to create the domain model. The basic structure was simple: Band  > Album > Track. I decided on a bottom-up approach. The Track class contained the following at first:


 public class Track
    {
        public int TrackNumber { get; set; }
        public string Name { get; set; }


        public static int CalculateTrackNumber(string  bandID, string albumID)
        {
            // finish
            throw new NotImplementedException();
        }
    }


I created that function as a stub because it relied on classes than didn't exist yet. The next class to create was the Album class:


public class Album
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public int Year { get; set; }
        public int CDNumber { get; set; }
        public List<Track> Tracks { get; set; }

        public static string GenerateID(string bandID)
        {
            throw new NotImplementedException();
        }
    }

The top layer of the model was the following:



    public class Band
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<Album> Albums { get; set; }
        public bool HasDescription { get; set; }
    }

As you can see, the Band class had no GenerateID function. That was because Raven was going to create the document IDs for me. Now I could fill in the stubs, first for the Album class...


       public static string GenerateID(string bandID)
        {
            // throw new NotImplementedException();
            var session = MvcApplication.documentStore.OpenSession();
            var band = session.Load<Band>(bandID);


            return "albums-" + (band.Albums.Count + 1).ToString();
        }


The session gave the method access to the database's documents. The next line retrieved the Band document whose ID matched bandID. The other method body was similar...



        public static int CalculateTrackNumber(string  bandID, string albumID)
        {
            // finish
            // throw new NotImplementedException();
            var session = MvcApplication.documentStore.OpenSession();
            var band = session.Load<Band>(bandID);


            var album = (from a in band.Albums
                         where a.Id == albumID
                         select a).First();


            return (album.Tracks.Count + 1); 
        }


Now hopefully you can see the method to my madness (pardon the pun). A Band object contains a List of albums, and each album contains a list of tracks. The next post will start the real fun... the controllers.









No comments:

Post a Comment