Using Upsert in Microsoft Dynamics CRM 2015 Update 1

Another useful feature that is introduced in Dynamics CRM 2015 update 1 is support for upsert operation. Upsert allows us to create or update record in CRM in single call, so we don't need to bother if there is any existing record with the same keys or combination of other fields. This is specially useful in case of integration, when we are not sure that record from other system is already integrated with CRM or not. We can use upsert with alternate keys, Please refer our earlier blog for how to use alternate keys. Let's take below example where we are writing a account request, using upsertrequest:
  1. Entity account = new Entity("account""accountnumber""UPST601");  
  2. account["name"] = "Upsert Demo";  
  3. account["revenue"] = new Money(5000);  
  4.   
  5. UpsertRequest request = new UpsertRequest()   
  6. {  
  7.     Target = account  
  8. };  
  9.   
  10. UpsertResponse response = (UpsertResponse) service.Execute(request);  
  11. if (response.RecordCreated) Console.WriteLine(account["name"] + " Created with Revenue: " + account.GetAttributeValue < Money > ("revenue").Value);  
  12. else Console.WriteLine(account["name"] + " Updated with Revenue: " + account.GetAttributeValue < Money > ("revenue").Value);  
  13.   
  14. Console.WriteLine("-----------------------------------");  
  15. account["revenue"] = new Money(15000);  
  16. UpsertRequest request1 = new UpsertRequest()   
  17. {  
  18.     Target = account  
  19. };  
  20. response = (UpsertResponse) service.Execute(request);  
  21. if (response.RecordCreated) Console.WriteLine(account["name"] + " Created with Revenue: " + account.GetAttributeValue < Money > ("revenue").Value);  
  22. else Console.WriteLine(account["name"] + " Updated with Revenue: " + account.GetAttributeValue < Money > ("revenue").Value);  
  23. Console.ReadLine();  
As you can see in above code we are executing upsert request two times, so first time as this record is not available in CRM, it will create it, but while executing next statement it will update existing record instead of creating it.

 

HIMBAP | Need any help in Microsoft CRM 2015 Development Contact US !! 
Ebook Download
View all
Learn
View all