Fetching Related Data in .NET Based Azure Mobile Service

While developing our app using Azure Mobile Services with a .Net backend, I was hit by a roadblock. As you may have guessed, the service was not loading the related data objects.

Searching the web did not reveal any useful information. But as usual, Stack Overflow came to help.

To better understand the scenario, let's write some code and see the problem ourselves.

Note: I will work on top of my last blog: create-multi-table-dot-net-azure-service-backend, WinPhone app in less than 30 steps:

Assuming that you have followed that example, we now have 2 model classes, as below.

model classes
 
classes

Where 1 user can have multiple To Do items.

Assuming that you have followed along the last example, we now have a solution where we can create To Do tasks for a user.

Now, if you have a need to fetch all To Do items and their user details and you write a query like this:
 
query
 
fetch all items

You will notice that the user data is not available by default in the returned collection for each of the To Do items. This is because Mobile Services does not, by default, traverse through the navigational properties to improve the performance.

As usual, there is a way to get this fixed. As suggested by a fellow stack overflow user (@JuneT) here.

According to June, we need to use the "$expand" property from our client-side code to ensure that Mobile Services traverses through the navigational properties and fetches the related data for us in the client.

To do this we need to modify our query above and use it like this instead:
 
modify our query

If you do a quick watch in the datalist object this time around, you will notice that indeed it now has the User property available for each of the To Do items.

This approach works great, neat!! What more could anyone want?

Yes, as you guessed, updating your client query calls to append and use the “$expand” property every time, on all screens, could be a bit tedious, plus it also does not looks like a very neat way of sorting this issue out.

This is where another Pro Stack Overflow user (@carlosfigueira) came to help. Seems like he had written a neat helper class that you can use on the service side to use the "expand" filter in your method calls.

Note: You can copy the ExpandPropertyAttribute class from his answer on my query here.

This is what you need to do on the service side to make this work.

Create a new class (use code from Carlos) on the service side of your project.
 
new class

And adorn your Method call in the To Do controller to use this expanderProperty attribute.
 
expanderProperty attribute

That's all. No changes required on the client side. All queries on the client side remains the same as the default:
 
queries on client side

This works like a charm and you can use the same helper for all your model classes.

You can also adorn more than one attributes if need be:
 
attributes 


Similar Articles