Search code examples
dynamics-crmdynamics-365dynamics-crm-365dynamics-crm-webapi

How to create Entity record with the predefined Id?


Is it possible to recreate the entity record with the predefined Id? The purpose of this question is to figure out how to create the entity record with the id you have provided.

For example when I delete Account record with the id '00-00-02' it does not exist in MS Dynamics CRM anymore. So now I want to recreate this Account record using REST API with it`s old id ('00-00-02'). Can anyone suggest me how to do it (or it is not possible)?


Solution

  • D365 allows you to set the primary key Guid of an entity. Often when doing data migrations from one D365 org to another we'll push the id's across.

    Here's an example of setting the accountId on a new account via the Web API. (Created in Jason Lattimer's CRMRESTBuilder):

    var entity = {};
    entity.accountid = "008A5AD9-59B7-43BB-BA41-BA59CB5B4769";
    entity.name = "Acme Inc.";
    
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts", true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function() {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 204) {
                var uri = this.getResponseHeader("OData-EntityId");
                var regExp = /\(([^)]+)\)/;
                var matches = regExp.exec(uri);
                var newEntityId = matches[1];
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send(JSON.stringify(entity));