Search code examples
azureforeign-key-relationshipazure-mobile-services

Azure Mobile Services : Foreign key table objects are null in Query


I have two classes on my Azure Mobile Service, I am using a .NET backend and using the code first approach for my database tables.

The two tables I am having issues with are Chip and PlayerChip.

I can insert data and query from them individually without any problems, however when I want to query a list of PlayerChip, and get the Name property on the Chip object belonging to the foreign key relation, the Chip object is null.

What is the best way to make sure the foreign key object is populated correctly?

Here are my table definitions...

public class PlayerChip : EntityData
    {
        [ForeignKey("Chip")]
        public string ChipId { get; set; }

        public virtual Chip Chip { get; set; }
    }

public class Chip : EntityData
    {
        public string Name { get; set; }
    }

Solution

  • This is more of an Entity framework question than anything to do with Mobile Services. However, in your controller, after you call the base class to get the specific item, you can add some code to load the Chip property.

    you can do something like this:

    dbContext.Entry(playerChip).Reference("Chip").Load();

    This assumes you have access to the db context (you'll need to add a field and set it in the initialize method). "playerChip" here refers to the object returned from the base class.

    A better solution might be to have the client request the inclusion of that property. GET https://yourservice.azure-mobile.net/tables/PlayerChip?$expand=Chip

    Then you get it when you want it in the client application, and not in all cases.

    The client SDKs allow you to add parameters to your request, so you can add $expand as one of those parameters.

    make sure your client model reflects that same relationship with a Playerchip having a Chip property reference.