Cover

MSchema: An Example - Part 2

December 29, 2008
No Comments.

Url: http://wilderminds.blob.core.windows.net/downloads/StudentSchema.zip
Silverlight Logo
If you have read Part 1 of this series, you have seen how to create types, collections and constraints using MSchema. Along with most database schemas, I find the need to create some amount of data to go along with those schemas. For my current project (our new web site), I wanted to have some small set of data that included some basic workshops and locations.

To create the data we can use the MGraph language. MGraph is related to MSchema but is a way of describing concrete instances of data. To create an instance:

module Training
{
  Workshop
  {
    {
      Name = "Silverlight Workshop",
      Description = "A three day workshop to teach Silverlight 2.",
      Length = 3,
      MaxAttendees = 16,
      DefaultPrice = 1800.00
    },
    {
      Name = "Advanced Silverlight",
      Description = "Two-day course teaching advanced Silverlight topics.",
      Length = 2,
      MaxAttendees = 16,
      DefaultPrice = 1200.00
    }
  }
}

The syntax looks similar to a mix between the C# object initialization syntax and JSON. The module matches the same module that the schema was defined in. Then it is the extent name (Workshop in this case) then an array of objects (notice the types defined inside curly braces). This can be used to generate insert statements. That’s easy to do with actual insert statements, so why learn this format at all?

Foreign keys are what make this fun. If we wanted to add an event (who has a reference to a Workshop) we would need to be able to tell the MGraph language how to make the reference. I innocently thought of this approach:

  Event
  {
    {
      WorkshopId = 1,
      EventDate =  2009-02-04     
    }
  }

I assumed that I could set the id’s manually then use them…to my surprise MGraph handles that better that I guessed.  how so?  The creation of the instances can be named.  So if we change the workshop creation to use names like so:

  Workshop
  {
    SilverlightWorkshop {
      Name = "Silverlight Workshop",
      Description = "A three day workshop to teach Silverlight 3.",
      Length = 3,
      MaxAttendees = 16,
      DefaultPrice = 1800.00
    },
    AdvancedSilverlight {
      Name = "Advanced Silverlight",
      Description = "Two-day course teaching advanced Silverlight topics.",
      Length = 2,
      MaxAttendees = 16,
      DefaultPrice = 1200.00
    }
  }

Now that the workshops are named, we can define our events with the names:

  Event
  {
    {
      WorkshopId = Workshop.SilverlightWorkshop,
      EventDate =  2009-02-04     
    }
  }

Now when we create the event, we can use the workshop (notice the Workshop is prefixed) to say that the workshop for this event is the one we created above.  M takes care of the rest.

In the next part, we will show the command-line tools you can use to store the schemas and data in the database.