Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23798

Clean way to do an upsert (update or insert) operation in Dynamics CRM 4

Currently, I'm using the following code to perform an 'upsert' in CRM

try
{
 crm.Create(c);
} 
catch (SoapException)
{
 crm.Update(c);
}

Am I right in assuming that this type of updating will wipe all existing information from my business entity? And if so, how can I get the entity to update from the repository? Do I need fetch, retrieve, or something like that?

Thanks.

Upvotes: 0

Views: 1106

Answers (1)

TeaDrivenDev
TeaDrivenDev

Reputation: 6629

Using exception handling for flow control is bad 99.99% of the time; in this case among other things because you never know what the actual reason for your SoapException is.

A much cleaner way would be to check whether your record's ID field has a value; if so, do an Update, if not, do a Create (and maybe add the resulting ID to your object if you use it further). (We've seen a Create on a record with an ID actually do an update years ago, but we've never been able to reproduce it.)

Other than that, @ckeller is perfectly right; an attribute that is null in your object (because it wasn't in the ColumnSet when retrieving from the database or hasn't been set otherwise) will not be touched in an Update.

Upvotes: 2

Related Questions