My friend Patrick asked on twitter if it was possible to expose data relationships in Mobile Services and since this is a common question I thought it might be worthy of a blog post. As you no doubt know, in Windows Azure Mobile Services your data is your own; that is – it’s your SQL database and there’s nothing abnormal about the data schema within – it’s a canonical representation of the data your client inserted via our JSON api. Which means it’s easy to use for reporting, analysis and you can easily back up your data – it’s just an Azure SQL database.

A core theme held throughout the design of Mobile Services was simplicity with enablement. That is, we wanted to make backend development easy for all kinds of developers, but avoid closing the gate on scenarios wherever possible.

In the public preview of Mobile Services we peeled back the client to keep it as thin and easy to use as possible and I think it’s a delight to use.

Of course, one of the great things about SQL Server is that it’s a relational database and, sometimes, you want to access those relationships at the client. In this post, I’ll show one of the ways you can do this today. In this case – using scripts.

Imagine we have two tables – Posts and Comments. You get the idea - Comments are related to Posts via a PostId property on the Comment. Here’s the two C# classes that would go into my client application (you don’t need a class/type in JS)

This is a fun example because I get to stretch my scripting legs. And we’re done (note, you could also just use T-SQL to perform a join in the database). We’ll now be sending JSON over the wire that has a comments array for each post!

public IJsonValue ConvertToJson(object instance)
{
// don't reverse the conversion. We don't // want to push the collection back up to// the mobile servicereturnnull;
}
}

And you should be golden. You’ll now have a populated List<Comment> for all posts you read from the Mobile Service (empty if there were no comments). Note that we don’t want to reverse the conversion as you don’t want to push the comments to the server on insert or update – a null works fine here.

JS (WinJS) client

In the JS world we have slightly less work to do as the object will automatically have the comments array property (JavaScript rocks at handling JSON – no surprise there). However, since you don’t want to push the comments back to the service, you should remember to delete that property before calling update, e.g.: