When you take the first two letters of the word update and last four letters of the word insert then you come up with a word Upsert. Now you know what Upsert will do. Yes, you are right Upsert will either update or insert. But how Upsert defines which records to go for an update and which one to go for insert. Well it depends on the data you pass to the upsert request. That is what I am going to explain in this blog.

When to use Upsert: When you are not sure if the data exists or you do not have the GUID of the data that needs to be update. Using upsert you can avoid the retrieve calls to CRM.

How upsert defines the record to be an update or insert: It uses alternate keys; yes you heard it right – Alternate Keys. This is a new concept introduced as a part of Update 01 and you can refer my blog on Alternate Keys here. If any record has a same value in the alternate key attribute that exists in CRM then that record is considered for an update. Also, if the record has a primary key GUID value which already exists in CRM then such records are also treated as update. All other records are treated as insert.

Flowchart:

Upsert flowchart

How to form the upsert request – Code:

public void ProcessUpsert(String Filename)
{
    Console.WriteLine("Executing upsert operation.....");
    XmlTextReader tr = new XmlTextReader(Filename);
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(tr);
    XmlNodeList xnlNodes = xdoc.DocumentElement.SelectNodes("/products/product");

    foreach (XmlNode xndNode in xnlNodes)
    {
        String productCode = xndNode.SelectSingleNode("Code").InnerText;
        String productName = xndNode.SelectSingleNode("Name").InnerText;
        String productCategory = xndNode.SelectSingleNode("Category").InnerText;
        String productMake = xndNode.SelectSingleNode("Make").InnerText;

        // Use alternate key for product
        // Define the Alternate key which uniquely identifies the record
        KeyAttributeCollection productkeys = new KeyAttributeCollection();
        productkeys.Add("sample_productcode", productCode);
        Entity productToCreate = new Entity("sample_product", productkeys); 
        
        // Specify product attributes to update
        productToCreate["sample_name"] = productName; 
        productToCreate["sample_category"] = productCategory; 
        productToCreate["sample_make"] = productMake; 

        // Create upsert request
        UpsertRequest request = new UpsertRequest() 
        { 
             Target = productToCreate 
        }; 

        try 
        { 
             // Execute UpsertRequest and obtain UpsertResponse. 
             UpsertResponse response = (UpsertResponse)_serviceProxy.Execute(request); 
             if (response.RecordCreated) 
                   Console.WriteLine("New record {0} is created!", productName); 
             else 
                   Console.WriteLine("Existing record {0} is updated!", productName); 
        } 
        // Catch any service fault exceptions that Microsoft Dynamics CRM throws. 
        catch (FaultException) 
        { 
              throw; 
        } 
    } 
    // Prompts to view the sample_product entity records. 
    // If you choose "y", IE will be launched to display the new or updated records. 
    if (PromptForView()) { ViewEntityListInBrowser(); } 
}

Things to note here is the Entity record defined in the code above has two parameters – first is the entity name sample_product second is the Alternate Key KeyAttributeCollection. There could be multiple Keys defined in the CRM on particular entity. Those all can be defined in this KeyAttributeCollection.

How to identify if the record got inserted or updated: The Upsert request also returns UpsertResponse. This has a property called RecordCreated which is a boolean value. This will let you know if the record got created or updated. If the value is true then the record got created; if it is false then the record got updated.

I am still experimenting around upsert and if any new findings I get then will update this blog. Until then if you have any questions feel free to leave a comment. You can also subscribe to email notifications down below.

Note: Upsert will only work on CRM Online which has updated to Dynamics CRM 2015 Update 01 only. This is not available for any on-premises versions.

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: