0

I have an Azure database with around 2k records and I'd like to retrieve one random record using the .NET client for Azure Mobile Services. Anyone know how to do this?

kernanb
  • 566
  • 2
  • 6
  • 19

1 Answers1

2

There are a couple of ways to accomplish this. If you want to do it from the client only, without changing any of the default logic on the server tables, then you can do it by sending a couple of requests: first one request that only retrieves the number of elements in your table, and the next one that asks for a random element:

var table = client.GetTable<TodoItem>();
var items1 = await table.IncludeTotalCount().Take(0).ToListAsync();
var count = ((ITotalCountProvider)items1).TotalCount;
var itemNumber = rndGen.Next(count);
var items2 = await table.Skip(itemNumber).Take(1).ToListAsync();
var item = items2.FirstOrDefault();

Another alternative is to change the server logic (for example, in a custom API) to select a single item, and then call that API. The thread at Select n random rows from SQL Server table has many options on how you can accomplish this.

Community
  • 1
  • 1
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171