This sample demonstrates how to query a table for entities. You will need to have previously created a table in the service in order to query entities from it. To get started, you'll need access to either a Storage or Cosmos DB account.
A TableClient
is needed to perform table-level operations like inserting and deleting entities within the table, so it is ideal for dealing with only a specific table. There are two ways to get a TableClient
:
- Call
GetTableClient
from theTableServiceClient
with the table name.
var tableClient2 = serviceClient.GetTableClient(tableName);
- Create a
TableClient
with a SAS URI, an endpoint andTableSharedKeyCredential
, or a connection string.
var tableClient3 = new TableClient(
new Uri(storageUri),
tableName,
new TableSharedKeyCredential(accountName, storageAccountKey));
If you are not familiar with creating tables, refer to the sample on creating and deleting tables.
The upsert operation combines the capabilities of insert and update unconditionally.
var entity = new TableEntity(partitionKey, rowKey)
{
{"Product", "Markers" },
{"Price", 5.00 },
{"Brand", "myCompany" }
};
// Entity doesn't exist in table, so invoking UpsertEntity will simply insert the entity.
await tableClient.UpsertEntityAsync(entity);
// Delete an entity property.
entity.Remove("Brand");
// Entity does exist in the table, so invoking UpsertEntity will update using the given UpdateMode, which defaults to Merge if not given.
// Since UpdateMode.Replace was passed, the existing entity will be replaced and delete the "Brand" property.
await tableClient.UpsertEntityAsync(entity, TableUpdateMode.Replace);
The update operation adds conditions to support optimistic concurrency.
// Get the entity to update.
TableEntity qEntity = await tableClient.GetEntityAsync<TableEntity>(partitionKey, rowKey);
qEntity["Price"] = 7.00;
// Since no UpdateMode was passed, the request will default to Merge.
await tableClient.UpdateEntityAsync(qEntity, qEntity.ETag);
TableEntity updatedEntity = await tableClient.GetEntityAsync<TableEntity>(partitionKey, rowKey);
Console.WriteLine($"'Price' before updating: ${entity.GetDouble("Price")}");
Console.WriteLine($"'Price' after updating: ${updatedEntity.GetDouble("Price")}");