0
votes

How to update particular record in azure mobile Service.

For Example I have a table in azure called country having two columns

  • country_id
  • country_name

If I want to update the record with country_id=5 from USA to United State of America. How to Perform this.

//Global Variable  
  private MobileServiceCollection<country, country> items;
        private IMobileServiceTable<country> todoTable = App.MobileService.GetTable<country>();
    class country
    {
    public string id { get; set; }
    public string country_name { get; set; }
    public int country_id { get; set; }
    }

private async void btnUpdate_Click(object sender, RoutedEventArgs e)
 {
var change = await todoTable
 .Where(todoItem => todoItem.country_name == tboxcName.Text)
    .ToListAsync();
  await todoTable.UpdateAsync(change);
    }

The above code I tried from this post, but did not find out.

2

2 Answers

1
votes

You might want to try this:

private async void btnUpdate_Click(object sender, RoutedEventArgs e)
 {
var change = await todoTable
 .Where(todoItem => todoItem.id.Equals(tboxcName.Text))
    .ToListAsync();

    if(change != null){
        var toChange= change.First();
        toChange.country_name="United State of America";
          await todoTable.UpdateAsync(toChange);
    }
    else{
    // you have nothing to change, you might throw an exception
    }
    }

In the textbox you should enter the id you want to update, in your case it's 5. Then I make a linq query selecting all the items with Id "5", this gets me a list. I check if the list is not void, you would want to threat the case when the list is null. If it's not null I take the first element (as you are in the mobile services the id field is unique in the database, so you don't have to threat this boundary case (although if you really want to be sure it's always better to do it)). The first element in the list will have the ID=5, so we change the object updating it's country name to "United States of America" (in your case, you don't care of the previous value, as you are updating a specific ID). Then you update this item. The mobile service API will then issue a patch request, and the database will patch it according to the Object ID.

Hope this helps!

0
votes

Try with this C# code!

private async void btnUpdate_Click(object sender, RoutedEventArgs e)
 {
   var filteredRecords = await todoTable.Where(
     todoItem => todoItem.country_id == 5)
     .ToListAsync();

   foreach (var item   in filteredRecords)
   {
     item.country_name="United States of America"; 
     await todoTable.UpdateAsync(item);
   }
 }