1

我们有一个名为 Question 的实体,它有多个响应,即 Question 和 Response 实体之间存在 1:N 的关系。

我们有一个现有的问题记录。我们需要能够实现的是更新 Question 记录,同时添加与同一个问题相关的多个 Response 记录(即,Response 表上的 new_QuestionId 字段应作为 Response 创建的一部分填充)。

我的逻辑是

  1. 更新问题记录(即,一次 PATCH 操作)。
  2. 具有循环结构并在循环内创建与问题记录相关的响应记录。

示例代码

所以,在这里我给出了一个示例,我们正在创建一个与问题相关的响应记录(带有记录 Id 4B5461DB-7061-E711-8124-E0071B66C0A1)。

POST [Organization URI]/api/data/v8.2/new_responses HTTP/1.1 
Content-Type: application/json; charset=utf-8 
OData-MaxVersion: 4.0 
OData-Version: 4.0 
Accept: application/json
{   
    "new_questionTitle": "This is the question from my console app",  
    "new_score": 100,   
    "new_nativelanguage": "This is in native language",   
    "new_englishtranslation": "This is in english",   
    "new_questionid@odata.bind": "/new_questions(4B5461DB-7061-E711-8124-E0071B66C0A1)",   
    "new_name": "This is the primary attribute" 
}

我的问题是,如果我希望能够创建多个响应,那么 JSON 会是什么,所有响应都与相同的问题 ID 相关4B5461DB-7061-E711-8124-E0071B66C0A1

我们在线使用 Dynamics 365。

4

1 回答 1

0

WebAPI 具有执行批处理请求的能力,如下所述:使用 Web API 执行批处理操作

Scaleable Solutions 的这篇博文包含以下批量创建示例代码:

function BulkCreate() {
    var body = "";
    var entityCollection = new Array();

    var entity1 = {};
    entity1["name"] = "dummy account 1";
    var body = JSON.stringify(entity1);
    entityCollection.push(body);

    body = "";
    var entity2 = {};
    entity2["name"] = "dummy account 2";
    body = JSON.stringify(entity2);
    entityCollection.push(body);

    var data = [];
    data.push('--batch_123456');
    data.push('Content-Type: multipart/mixed;boundary=changeset_BBB456');
    data.push('');

    for (var i = 0; i < entityCollection.length; i++) {
        data.push('--changeset_BBB456');
        data.push('Content-Type:application/http');
        data.push('Content-Transfer-Encoding:binary');
        var id = i + 1;
        data.push('Content-ID:' + id);
        data.push('');
        data.push('POST ' + parent.Xrm.Page.context.getClientUrl() + '/api/data/v8.1/accounts HTTP/1.1');

        data.push('Content-Type:application/json;type=entry');
        data.push('');
        data.push(entityCollection[i]);
    }

    data.push('--changeset_BBB456--');
    data.push('--batch_123456--');
    var payload = data.join('\r\n');
    $.ajax(
    {
        method: 'POST',
        url: parent.Xrm.Page.context.getClientUrl() + '/api/data/v8.1/$batch',
        headers: {
            'Content-Type': 'multipart/mixed;boundary=batch_123456',
            'Accept': 'application/json',
            'Odata-MaxVersion': '4.0',
            'Odata-Version': '4.0'
        },
        data: payload,
        async: false,
        success: function (data, textStatus, xhr) {
            alert("Record has been successfully Created");
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(textStatus + " " + errorThrown);
        }
    });
}
于 2017-07-12T19:35:46.040 回答