使用代码对弹性表执行数据操作

本文介绍如何使用代码对 Dataverse 弹性表执行数据操作。 了解如何使用适用于 .NET 的 SDK 或 Web API 创建、检索、更新、更新插入、删除、查询和关联弹性表记录,以及如何使用会话令牌、分区 ID 值和批量操作。

使用会话令牌

如 一致性级别中所述,可以通过向请求传递当前会话令牌来实现会话级一致性。 如果未包含会话令牌,检索的数据可能不包括刚刚进行的数据更改。

获取会话令牌

会话令牌在所有写入操作的响应中可用。 查找 x-ms-session-token 值。

对于执行写入操作的任何 OrganizationResponse,您都可以在结果集合中捕获 x-ms-session-token 值。

Note

DeleteResponse 当前不返回 x-ms-session-token 值。 有关详细信息,请参阅 已知问题:删除操作不返回 x-ms-session-token 值。

string sessionToken = response.Results["x-ms-session-token"].ToString();

发送会话令牌

在读取操作中发送会话令牌的方法取决于使用的是 SDK 还是 Web API。

执行检索数据的操作时,请在 OrganizationRequest 上设置 SessionToken 这个可选参数。

var request = new RetrieveRequest
{
    Target = new EntityReference("contoso_sensordata", sensordataid),
    ColumnSet = new ColumnSet("contoso_value"),
    ["partitionId"] = deviceId,
    ["SessionToken"] = sessionToken
};

详细了解如何使用可选参数。

指定 PartitionId

如 分区和水平缩放中所述,每个弹性表都有一个 partitionid 列,如果选择为表应用分区策略,则必须使用该列。 否则,不要为 partitionid 列设置值。

Important

如果选择对弹性表使用分区策略,则对该表执行的所有操作或引用该表中记录的所有操作 必须 指定 partitionid 列值以唯一标识该记录。 如果未在引用表的查找值中指定 partitionid ,则不会出错,但使用它时,查找将无法定位该记录。 必须通过代码评审记录并强制实施此要求,以确保数据保持一致,并在所有操作中适当使用 partitionid。

在创建行时为 partitionid 列指定非 null 值后,必须在对该行执行任何其他数据操作时指定该值。 以后无法更改该值。

如果在创建记录时未为记录设置 partitionid 值,则 partitionid 列值将保留为 null,并且以后无法更改该值。 在这种情况下,可以使用主键来标识记录,就像使用标准表一样。 无需指定 partitionid 值。

Note

本文中的示例假定你为 partitionid 列指定了非 null 值。

执行各种数据操作时,可以通过以下方式设置 partitionid 值。

使用备用键

如备用键中所述,每个弹性表都有一个名为 KeyForNoSqlEntityWithPKPartitionId 的备用键。 此备用键将表的主键与 partitionid 列组合在一起。

如果使用分区策略,则必须指定备用键,以便在使用 Retrieve、Update 或 Delete 操作时指定 partitionid 值,或者在为另一个引用弹性表记录的表设置查找列时指定 partitionid 值。

此示例演示如何使用备用键在弹性表上使用Update、Delete和partitionid请求时指定Retrieve值。

var keys = new KeyAttributeCollection() {
    { "contoso_sensordataid", sensordataid },
    { "partitionid", deviceId }
};

var entity = new Entity("contoso_sensordata", keys)

使用 partitionId 参数

目前,仅可在partitionid和Delete操作中使用参数partitionId指定Retrieve列的值。 有关详细信息,请参阅 已知问题:partitionId 可选参数不适用于所有消息。

Note

参数 partitionId 不适用于 Create、 Update或 Upsert 消息,如果发送该参数,服务将忽略它。

request["partitionId"] = "device-001"

直接使用 partitionid 列

对于 Create、Upsert 或 Update 操作,可以直接指定 partitionid 列的值。

此示例演示如何在执行 Create、Entity 或 partitionid 操作时,直接指定 Update 中 Upsert 列的值。

var entity = new Entity("contoso_sensordata", sensordataid)
{
    Attributes = {
        { "partitionid", "device-001" }
    }
};

在弹性表中创建记录

本示例在 contoso_SensorData 表中创建一行,在其中将 partitionid 设置为 deviceid。 它还设置 ttlinseconds 列,以确保行在一天后(86,400 秒)过期,并自动从 Dataverse 中删除。

此示例还会捕获 x-ms-session-token 值,您可以在检索已创建的记录时使用该值。

/// <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;
}

检索创建的记录时,使用返回 x-ms-session-token 的值设置 SessionToken 可选参数。 详细了解如何发送会话令牌。

Note

弹性表不支持 深度插入。 需要单独创建每个相关记录。 只有标准表支持深度插入。

设置主键值

如果未指定主键值,则创建记录时,Dataverse 将为记录设置主键值。 让 Dataverse 设置此值是正常的做法。 如果需要,可以指定主键值。 对于弹性表,让 Dataverse 设置主键值没有性能优势。

Dataverse 将主键数据存储在遥测中,以帮助维护服务。 如果指定自定义的主键值,请不要在这些值中使用敏感信息。

创建主键值不唯一的记录时,弹性表不会返回错误。 通过在弹性表中设置主键值,您可以创建具有相同主键值但 partitionid 值不同的记录。 但是,此模式与Power Apps不兼容。 当需要在画布或模型驱动应用中使用此数据时,不要创建具有重复主键值的记录。

更新弹性表中的记录

此示例通过使用 contoso_timestamp 主键和 contoso_SensorDatacontoso_sensordataidcontoso_value,更新 = 表中现有行的 'device-001' 和 partitionid 值。

如果使用分区策略,主键和 partitionid 列必须唯一标识现有的弹性表行。 无法更新 partitionid 现有行的值。 它仅用于唯一标识要更新的行。

此示例使用 KeyForNoSqlEntityWithPKPartitionId 备用键通过主键和 partitionid 值来唯一标识记录。 详细了解备用键。

此示例演示如何将 partitionid 值用作备用键。

/// <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();
}

详细了解如何使用 Entity 类设置备用键。

检索弹性表中的记录

如果在创建弹性表记录时设置 partitionid 该值,请将其与主键值一起使用以唯一标识记录。

如果未设置 partitionid 该值,则仅使用主键值检索记录。

若要使用 partitionid 该值检索记录,请通过以下方式之一撰写请求。

此示例使用 RetrieveRequest 类。 将Target属性设置为使用接受KeyAttributeCollection的构造函数创建的EntityReference,以使用KeyForNoSqlEntityWithPKPartitionId备用键。 详细了解如何将 EntityReference 类与备用键配合使用。

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")}");
}

此示例在 partitionId 上使用一个名为 的可选参数。 详细了解如何使用可选参数。

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")}");
}

查询弹性表的行

查询弹性表的行时,如果将查询限制为特定分区,将获得最佳性能。 否则,查询将返回所有逻辑分区的数据,这并不快。

Note

使用这种方法时,参数必须使用名称 partitionId(其中 I 为大写),而不是 partitionid(全部为小写字母)。

以这种方式指定筛选器时,不必以通常的方式在查询中在 partitionid 上指定筛选条件(即使用 FetchXML condition、QueryExpressionConditionExpression 或 Web API $filter)。

以平常方式对 partitionid 值指定筛选器,与通过 partitionId 参数指定相比,不具备相同的性能优势,如以下示例所示。

这些示例检索 contoso_SensorData 表中属于逻辑分区(其中 = partitionid'deviceid-001')的前 500 行。

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;
}

运行查询时,弹性表当前不支持返回相关行。 如果尝试返回相关行,Dataverse 将引发代码 0x80048d0b 错误,并显示以下消息:

Link entities are not supported。

但是,当你检索单个行时,弹性表确实支持返回相关行。

在弹性表中插入或更新记录

Important

弹性表的 Upsert 操作不同于标准表的 upsert 操作。 Upsert 操作应包含完整有效负载并覆盖任何现有记录数据。 它们不会调用 Create 或 Update 消息。 详细了解弹性表 upsert。

使用弹性表时,如果不存在具有给定 ID 和 partitionid 的记录,则会创建该记录。 如果已存在,则将其替换。

本示例对 contoso_SensorData 表中具有指定 id 值和 partitionid = deviceid-001 的一行执行 upsert(插入或更新)操作。

/// <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;
}

删除弹性表中的记录

删除使用自定义 partitionid 值的记录时,必须包含 partitionid 值。

此示例删除 contoso_SensorData 表中具有指定 ID 和 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();
}

关联弹性表记录

当表记录引用了 partitionid 列值为 null 的弹性表记录时,您可以像处理标准记录一样,将该表中的记录与弹性表记录关联起来。 请参阅 适用于 .NET 的 SDK或 Web API。

当表记录引用设置了 partitionid 列值的弹性表记录时,在设置引用表的查找列时,必须包含该弹性表记录的 partitionid 列值。 可以通过将该值包含为备用键值来执行此操作。

如引用表中的 Partitionid 值列所述,当创建一对多关系且弹性表是被引用表时,会在引用表上创建一个字符串列和一个查找列。 字符串列存储被引用的弹性表记录的 partitionid 值。

可以通过以下方法设置查找值和字符串列值:

  • 使用备用键引用以仅设置查找
  • 在一次更新中将两列值设置在一起

具体操作方式取决于是使用 SDK 进行.NET还是 Web API。

此示例通过使用备用键设置查找列,将具有指定 ID 和 partitionid 的弹性 contoso_SensorData 表记录与现有帐户记录相关联:

/// <summary>
/// Demonstrates associate to elastic table 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="deviceId">The deviceId. PartitionId of sensor data record.</param>
/// <param name="accountId">The unique identifier of the account record to update.</param>
public static void AssociateAccountAlternateKeyExample(
    IOrganizationService service,
    Guid sensordataId,
    string deviceId,
    Guid accountId)
{
    var keys = new KeyAttributeCollection() {
        { "contoso_sensordataid", sensordataId },
        { "partitionid", deviceId }
    };

    var sensorDataReference = new EntityReference("contoso_sensordata", keys);

    Entity account = new("account", accountId)
    {
        Attributes =
            {
                {"contoso_sensordata", sensorDataReference}
            }
    };

    service.Update(account);
}

此示例执行相同的操作,但同时设置这两列:

/// <summary>
/// Demonstrates associate to elastic table 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="deviceId">The deviceId. PartitionId of sensor data record.</param>
/// <param name="deviceId">The unique identifier of the account record to update.</param>
public static void AssociateAccountBothColumnsExample(
    IOrganizationService service,
    Guid sensordataId,
    string deviceId,
    Guid accountId)
{
    Entity account = new("account", accountId) {
        Attributes =
            {
                {"contoso_sensordata", new EntityReference("contoso_sensordata", sensordataId)},
                {"contoso_sensordatapid", deviceId }
            }
    };

    service.Update(account);
}

最后,此示例演示了如何使用 AssociateRequest 在一次操作中将一组 account 记录关联到同一 contoso_SensorData 表记录。

/// <summary>
/// Demonstrates associating multiple accounts to a contoso_sensordata elastic table record
/// </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 deviceId. PartitionId of sensor data record.</param>
/// <param name="relatedEntities">A collection of references to account records to associate to the contoso_sensordata elastic table record</param>
public static void AssociateMultipleElasticTableExample(
   IOrganizationService service,
   Guid sensordataId,
   string deviceId,
   EntityReferenceCollection relatedEntities)
{

   // The keys to the elastic table record including the partitionid
   var keys = new KeyAttributeCollection() {
         { "contoso_sensordataid", sensordataId },
         { "partitionid", deviceId }
   };

   AssociateRequest request = new()
   {
         Target = new EntityReference("contoso_sensordata", keys),
         Relationship = new Relationship("contoso_SensorData_contoso_SensorData_Acc"),
         RelatedEntities = relatedEntities
   };

   service.Execute(request);
}

使用弹性表执行批量操作

通常,应用程序必须在短时间内将大量数据引入 Dataverse。 Dataverse 有一组旨在实现高吞吐量的消息集。 使用弹性表时,吞吐量可能更高。

当对同一个表执行多个写入操作时,批量操作通过采用单个写入操作中的一批行作为输入来优化性能。 详细了解批量操作消息(预览版)。

将 CreateMultiple 与弹性表配合使用

可以将CreateMultiple消息与 SDK for .NET 或 Web API 配合使用。

此示例使用 CreateMultipleRequest 类 在 contoso_SensorData 弹性表中创建多行。

public static Guid[] CreateMultiple(IOrganizationService service)
{
    string tableLogicalName = "contoso_sensordata";

    List<Microsoft.Xrm.Sdk.Entity> entityList =
    [
        new (tableLogicalName)
        {
            Attributes =
            {
                { "contoso_deviceId", "deviceid-001" },
                { "contoso_sensortype", "Humidity" },
                { "contoso_value", "40" },
                { "contoso_timestamp", "2023-05-01Z05:00:00"},
                { "partitionid", "deviceid-001" },
                { "ttlinseconds", 86400 }
            }
        },
        new (tableLogicalName)
        {
            Attributes =
            {
                { "contoso_deviceId", "deviceid-002" },
                { "contoso_sensortype", "Humidity" },
                { "contoso_value", "10" },
                { "contoso_timestamp", "2023-05-01Z09:30:00"},
                { "partitionid", "deviceid-002" },
                { "ttlinseconds", 86400 }
            }
        },
        new (tableLogicalName)
        {
            Attributes =
            {
                { "contoso_deviceId", "deviceid-002" },
                { "contoso_sensortype", "Pressure" },
                { "contoso_value", "20" },
                { "contoso_timestamp", "2023-05-01Z07:20:00"},
                { "partitionid", "deviceid-002" },
                { "ttlinseconds", 86400 }
            }
        }
    ];

    // Create an EntityCollection populated with the list of entities.
    EntityCollection entities = new(entityList)
    {
        EntityName = tableLogicalName
    };

    // Use CreateMultipleRequest
    CreateMultipleRequest createMultipleRequest = new()
    {
        Targets = entities,
    };

    var createMultipleResponse = (CreateMultipleResponse)service.Execute(createMultipleRequest);
    return createMultipleResponse.Ids;
}

将 UpdateMultiple 与弹性表配合使用

可以将UpdateMultiple消息与 SDK for .NET 或 Web API 配合使用。

此示例使用 UpdateMultipleRequest 类 更新 contoso_SensorData 弹性表中的多行。 这些更新设置了 contoso_value 列。

public static void UpdateMultiple(IOrganizationService service)
{
    string tableLogicalName = "contoso_sensordata";

    List<Microsoft.Xrm.Sdk.Entity> entityList =
    [
        new(tableLogicalName, new Guid("6114ca58-0928-ee11-9965-6045bd5cd155"))
        {
            Attributes =
            {
                { "contoso_value", "45" },
                { "partitionid", "deviceid-001" }
            }
        },
        new(tableLogicalName, new Guid("6214ca58-0928-ee11-9965-6045bd5cd155"))
        {
            Attributes =
            {
                { "contoso_value", "15" },
                { "partitionid", "deviceid-002" }
            }
        },
        new(tableLogicalName, new Guid("6314ca58-0928-ee11-9965-6045bd5cd155"))
        {               
            Attributes =
            {
                { "contoso_value", "25" },
                { "partitionid", "deviceid-002" }
            }
        }
    ];

    // Create an EntityCollection populated with the list of entities.
    EntityCollection entities = new(entityList)
    {
        EntityName = tableLogicalName
    };

    // Use UpdateMultipleRequest
    UpdateMultipleRequest updateMultipleRequest = new()
    {
        Targets = entities,
    };

    service.Execute(updateMultipleRequest);
}

将 DeleteMultiple 与弹性表配合使用

可以将DeleteMultiple消息与 SDK for .NET 或 Web API 配合使用。

以下 DeleteMultipleExample 静态方法结合使用 DeleteMultiple 消息与 OrganizationRequest 类,从 contoso_SensorData 弹性表中删除多行。 备用键包括 partitionid 值,用于唯一标识这些行。

Note

DeleteMultipleRequest 类现已可供使用。

public static void DeleteMultipleExample(IOrganizationService service)
{
    string tableLogicalName = "contoso_sensordata";

    List<EntityReference> entityReferences = new() {
        {
            new EntityReference(logicalName: tableLogicalName,
                keyAttributeCollection: new KeyAttributeCollection
                {
                    { "contoso_sensordataid", "3f56361a-b210-4a74-8708-3c664038fa41" },
                    { "partitionid", "deviceid-001" }
                })
        },
        { new EntityReference(logicalName: tableLogicalName,
            keyAttributeCollection: new KeyAttributeCollection
            {
                { "contoso_sensordataid", "e682715b-1bba-415e-b2bc-de9327308423" },
                { "partitionid", "deviceid-002" }
            })
        }
    };

    DeleteMultipleRequest request = new()
    {
        Targets = new EntityReferenceCollection(entityReferences)
    };

    service.Execute(request);
}

后续步骤

了解如何使用代码在弹性表中的 JSON 列中创建和查询 JavaScript 对象表示法(JSON)数据。

另请参阅

面向开发人员的 Elastic 表
使用代码创建弹性表
查询弹性表中的 JSON 列
弹性表示例代码
批量操作消息(预览版)