How do you get the Id field for a newly inserted item using the .NET client for Azure Mobile

421 views Asked by At

I'm trying to use Azure Mobile Services to create a backend for an asynchronous multiplayer game. I'm using a sql database and a .NET backend on WAMS, calling the service from the .NET client (Xamarin.iOS specifically atm).

The class for the item being into the db:

public class Match {
    public string Id { get; set; }
    public int Challengers { get; set; }
    string GameData { get; set; }
    public List<string> Players { get; set; }
    public string LastPlayer { get; set; }
    public string Message { get; set; }
    public string NextPlayer { get; set; }
    public int PlayerGroup { get; set; }
}

I'm inserting it into the database using:

var matchtable = MobileService.GetTable <Match> ();
CurrentMatch = new Match {
                Message = variant.ToString () + ", " + CurrentUser + " vs ??",
                NextPlayer = CurrentUser,
                Players = players,
                PlayerGroup = playerGroup,
                Challengers = 0,
                Game = null,
                LastPlayer = null
            };
await matchtable.InsertAsync (CurrentMatch);

I'm then doing other things that will affect the match and need to update it again later, but I don't have an Id field for the CurrentMatch to be able to do the update. Everything I can find tells me that I should get the Id field back after the insert (either the method returning something or updating CurrentMatch itself with it), but it must all be talking about a javascript backend or different client or something. The InsertAsync method in the .NET client has no return value (well, technically returns Task) and the CurrentMatch doesn't get updated with the Id field from the call (also makes sense since it's not a ref or out parameter).

How on earth am I supposed to get the Id field for an object I just inserted into the database?

1

There are 1 answers

0
lindydonna On

I'm assuming you are using the latest version of the Mobile Services client SDK, in which case you are calling this InsertAsync method here.

You're right that the parameter is not a ref or out parameter, but it can modify the fields of the object you passed in. In this case, it will modify the contents of the Match object.

My guess is that there is another code issue that's interfering. Or, if that code snippet is in a method, make sure it returns a Task and you await it before you check the contents of Id. A simple console log should help here.

If this doesn't solve the problem, then please include more context, otherwise the code you've written should behave as I've said.