Friday, February 8, 2013

Create Parent and Related Child records using Rest endpoints - Deep Insert Technique


A typical SDK approach of creating the Parent and Child records involves creating them individually and establishing the relationship between them. But this approach will eventually degrade the performance if the application needs to import more child records for the parent record. The limitation could be addressed in MSCRM 2011 using Deep Insert Technique.
Deep insert is a technique in which multiple child/related records can be created in the single operation while creating Parent record.  This way both parent and its related child records are created at the same time in CRM.
Below is an example where quote and its related quote products are created in CRM with a single OData Rest endpoint create operation.

 Steps followed are:
1.       Create a new Quote Object
2.       Create a new Quote Products Objects (can be multiple)
3.       Associate Quote products Object Array to Quote Object with the corresponding relationship name (here Quote_quoteproducts)
4.       Create the records in CRM using the Rest Endpoints with the Quote Object. (This will create both Quote & Quote Products).
// declare object to store the Quote
var quote = new Object();
quote.Name = "Sample Quote";
 

// declare object to store the Quote Products
var QuoteProduct1 = new Object();
QuoteProduct1.ProductDescription = "Quote Product 1 Name"; 

var QuoteProduct2 = new Object();
QuoteProduct2.ProductDescription = "Quote Product 2 Name"; 

// declare Array to push quote products

var QuoteProducts = new Array();
QuoteProducts.push(QuoteProduct1);
QuoteProducts.push(QuoteProduct2); 

quote.Quote_quoteproducts = QuoteProduct; 

// Json Stringfy method
var jsonQuote = window.JSON.stringify(quote);

var ODataPath = Xrm.Page.getServerUrl() + "/XRMServices/2011/OrganizationData.svc"

$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "/QuoteSet",
data: jsonQuote,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept","application/json");
},
success: function (data, textStatus, XmlHttpRequest) { },
error: function (XMLHttpRequest, textStatus, errorThrown) { }
}); 
Note - We can use the same method to create related activities and other records using the relationship.

No comments:

Post a Comment