Use elastic tables using code (preview)
[This topic is pre-release documentation and is subject to change.]
This article describes how to perform data operations on elastic tables using code.
Work with session token
As mentioned in Consistency level, you can achieve session level consistency by passing the current session token with your requests. If you don't include the session token, the data you retrieve may not include data changes you have just made.
Getting the session token
Find the session token as x-ms-session-token value in the response of all write operations.
For any OrganizationResponse that performs a write operation, you can capture the x-ms-session-token in the Results collection.
Note
DeleteResponse does not currently return the x-ms-session-token. More information: Known issues: x-ms-session-token value not returned for delete operations
string sessionToken = response.Results["x-ms-session-token"].ToString();
Sending the session token
How you send the session token in a read operation depends on whether you're using the SDK or Web API.
When performing an operation that retrieves data, set the SessionToken optional parameter on the OrganizationRequest.
var request = new RetrieveRequest
{
Target = new EntityReference("contoso_sensordata", sensordataid),
ColumnSet = new ColumnSet("contoso_value"),
["partitionId"] = deviceId,
["SessionToken"] = sessionToken
};
More information: Use optional parameters
Specifying PartitionId
As mentioned in Partitioning and horizontal scaling, each elastic table has a partitionid column that you must use if you choose to apply a partitioning strategy for the table. Otherwise, don't set a value for the partitionid column.
Once you have specified a non-null value to the partitionid column while creating a row, you must specify it when performing any other data operation on the row. You can't change this value later.
If you don't set a partitionid for a record when it's created, the partitionid column value remains null and you can't change it later. In this case, you can identify records using the primary key as you normally do with standard tables. Specifying partitionid isn't required.
Note
The examples in this article assume that you are specifying a non-null value to the partitionid column.
You can set the partitionid value in following ways when performing various data operations.
Using Alternate Key
As mentioned in Alternate keys, every elastic table has an alternate key named KeyForNoSqlEntityWithPKPartitionId. This alternate key combines the primary key of the table with the partitionid column.
You can use this alternate key to specify partitionid when using Retrieve, Update or Delete operations.
This example shows how you can use alternate key to specify partitionid when using Retrieve, Update and Delete requests on elastic tables.
var keys = new KeyAttributeCollection() {
{ "contoso_sensordataid", sensordataid },
{ "partitionid", deviceId }
};
var entity = new Entity("contoso_sensordata", keys)
Using partitionId parameter
Currently, you can use a partitionId parameter to specify the value of partitionid column only for Retrieve and Delete operations. More information: Known Issue: partitionId optional parameter not available for all messages
Note
partitionId parameter will not work with Create, Update or Upsert messages and will be ignored if sent.
request["partitionId"] = "device-001"
Using partitionid column directly
For Create, Upsert or Update operations, you can directly specify the value of partitionid column.
This example shows how you can directly specify the partitionid column in Entity when executing a Create, Upsert, or Update operation.
var entity = new Entity("contoso_sensordata", sensordataid)
{
Attributes = {
{ "partitionid", "device-001" }
}
};
Create a record in an elastic table
This example creates a new row in contoso_SensorData table with partitionid set to deviceid. It also sets ttlinseconds column that ensures that row expires after one day (86,400 seconds) and deleted from Dataverse automatically.
These examples also capture the value of the x-ms-session-token that you can use when retrieving the created record.
/// <summary>
/// Demonstrates creating a record with a partitionid and capturing the session token
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="deviceId">The value used as partitionid for the contoso_sensordata table. </param>
/// <param name="sessionToken">The current session token</param>
/// <returns>The Id of the created record.</returns>
public static Guid CreateExample(
IOrganizationService service,
string deviceId,
ref string sessionToken )
{
var entity = new Entity("contoso_sensordata")
{
Attributes =
{
{ "contoso_deviceid", deviceId },
{ "contoso_sensortype", "Humidity" },
{ "contoso_value", 40 },
{ "contoso_timestamp", DateTime.UtcNow},
{ "partitionid", deviceId },
{ "ttlinseconds", 86400 } // 86400 seconds in a day
}
};
var request = new CreateRequest {
Target = entity
};
var response = (CreateResponse)service.Execute(request);
// Capture the session token
sessionToken = response.Results["x-ms-session-token"].ToString();
return response.id;
}
Use the x-ms-session-token value returned to set the SessionToken optional parameter when retrieving the record you created. More information: Sending the session token
Update a record in an elastic table
This example updates the contoso_value and contoso_timestamp values of an existing row in contoso_SensorData table using the contoso_sensordataid primary key and partitionid = 'device-001'.
If you're using a partitioning strategy, the primary key and partitionid columns are required to uniquely identify an existing elastic table row. The partitionid of an existing row can't be updated and is only being used to uniquely identify the row to update.
This example uses the KeyForNoSqlEntityWithPKPartitionId alternate key to uniquely identify the record using both the primary key and the partitionid. More information: Alternate keys
This example shows using the partitionid value as an alternate key.
/// <summary>
/// Demonstrates updating elastic table row with partitionid as alternate key.
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="sensordataid">The unique identifier of the contoso_sensordata table.</param>
/// <param name="deviceId">The value used as partitionid for the contoso_sensordata table. </param>
/// <param name="sessionToken">The current session token</param>
public static void UpdateExample(
IOrganizationService service,
Guid sensordataid,
string deviceId,
ref string sessionToken)
{
var keys = new KeyAttributeCollection() {
{ "contoso_sensordataid", sensordataid },
{ "partitionid", deviceId }
};
var entity = new Entity("contoso_sensordata", keys)
{
Attributes = {
{ "contoso_value", 60 },
{ "contoso_timestamp", DateTime.UtcNow }
}
};
var request = new UpdateRequest {
Target = entity,
["SessionToken"] = sessionToken
};
var response = (UpdateResponse)service.Execute(request);
// Capture the session token
sessionToken = response.Results["x-ms-session-token"].ToString();
}
More information: Use an alternate key to reference a record > Using the Entity class
Retrieve a record in an elastic table
If an elastic table record was created setting the partitionid value, you must use the partitionid value together with the primary key value to uniquely identify a record.
If the partitionid wasn't set, you can retrieve the record normally using only the primary key value.
There are two different ways to compose a request to retrieve a record using the partitionid value.
This example uses the RetrieveRequest class with the Target property set to an EntityReference created using the constructor that accepts a KeyAttributeCollection to use the KeyForNoSqlEntityWithPKPartitionId alternate key. More information: Using the EntityReference class
public static void RetrieveExampleAlternateKey(IOrganizationService service, Guid sensorDataId, string deviceId) {
var keys = new KeyAttributeCollection() {
{ "contoso_sensordataid", sensorDataId },
{ "partitionid", deviceId }
};
var entityReference = new EntityReference("contoso_sensordata", keys);
var request = new RetrieveRequest {
ColumnSet = new ColumnSet("contoso_value"),
Target = entityReference
};
var response = (RetrieveResponse)service.Execute(request);
Console.WriteLine($"contoso_value: {response.Entity.GetAttributeValue<int>("contoso_value")}");
}
This example uses an optional parameter named partitionId on the RetrieveRequest class. More information: Use optional parameters
public static void RetrieveExampleOptionalParameter(IOrganizationService service, Guid sensorDataId, string deviceId)
{
var entityReference = new EntityReference("contoso_sensordata", sensorDataId);
var request = new RetrieveRequest
{
ColumnSet = new ColumnSet("contoso_value"),
Target = entityReference,
["partitionId"] = deviceId
};
var response = (RetrieveResponse)service.Execute(request);
Console.WriteLine($"contoso_value: {response.Entity.GetAttributeValue<int>("contoso_value")}");
}
Query rows of an elastic table
When you query the rows of an elastic table, you get best performance if you limit your query to a specific partition. If you don't limit your query to a specific partition, your query returns data across all logical partitions, which isn't as fast.
Note
When used this way, the parameter must use the name partitionId (capital 'I') rather than partitionid (all lower case).
When specifying a filter this way, you don't need to specify the filter criteria on partitionid in your query in the normal manner (using FetchXML condition, QueryExpression ConditionExpression, or Web API $filter.)
A filter on the partitionid value in the normal manner will not have the same performance benefits as specifying it with the partitionId shown below.
These examples retrieve the first 5000 rows in the contoso_SensorData table that belong to logical partitionid = 'deviceid-001'.
public static EntityCollection RetrieveMultipleExample(IOrganizationService service)
{
var request = new RetrieveMultipleRequest
{
Query = new QueryExpression("contoso_sensordata")
{
ColumnSet = new ColumnSet("contoso_value")
},
["partitionId"] = "deviceid-001"
};
var response = (RetrieveMultipleResponse)service.Execute(request);
return response.EntityCollection;
}
Return related rows in a query
Elastic tables currently don't support returning related rows when executing a query.
Dataverse throws an error with code 0x80048d0b and message Link entities are not supported when trying to do so.
However, elastic tables support returning related rows when retrieving a single row.
Upsert a record in an elastic table
Important
Upsert operations with elastic tables are different than with standard tables. Upsert operations are expected to contain the full payload and will over-write any existing record data. Upsert operations will not call the Create or Update messages. More information: Use Upsert to Create or Update a record > Elastic table upsert
With elastic tables, if a record with a given ID and partitionid doesn't exist, it's created. If it already exists, it's replaced.
This example upserts a row in the contoso_SensorData table with the specified id and partitionid = deviceid-001.
/// <summary>
/// Demonstrates an upsert operation
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="id">The id of the record to update or create.</param>
/// <param name="sessionToken">The current session token</param>
/// <returns>Whether a record was created or not</returns>
public static bool UpsertExample(IOrganizationService service, Guid id, ref string sessionToken)
{
var entity = new Entity("contoso_sensordata", id)
{
Attributes = {
{ "contoso_deviceid", "deviceid-001" },
{ "contoso_sensortype", "Humidity" },
{ "contoso_value", 60 },
{ "contoso_timestamp", DateTime.UtcNow },
{ "partitionid", "deviceid-001" },
{ "ttlinseconds", 86400 }
}
};
var request = new UpsertRequest
{
Target = entity,
["SessionToken"] = sessionToken
};
var response = (UpsertResponse)service.Execute(request);
// Capture the session token
sessionToken = response.Results["x-ms-session-token"].ToString();
return response.RecordCreated;
}
Delete a record in an elastic table
When deleting a record that uses a custom partitionid value, you must include the partitionid value.
This example deletes a row in contoso_SensorData table with specified ID and partitionid = 'deviceid-001'.
/// <summary>
/// Demonstrates a delete operation
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="sensordataid">The unique identifier of the contoso_sensordata table.</param>
/// <param name="sessionToken">The current session token</param>
public static void DeleteExample(
IOrganizationService service,
Guid sensordataid,
ref string sessionToken)
{
var request = new DeleteRequest
{
Target = new EntityReference("contoso_sensordata", sensordataid),
["partitionId"] = "deviceid-001"
};
var response = service.Execute(request);
// Known issue: Value not currently being returned.
// sessionToken = response.Results["x-ms-session-token"].ToString();
}
Next steps
Learn how to create and query JSON data in JSON columns in elastic tables with code
See also
Elastic tables (preview)
Create elastic tables using code
Bulk operations with elastic tables
Query JSON columns in elastic tables (preview)
Elastic table sample code (preview)
Feedback
Submit and view feedback for