Tuesday, January 20, 2009

No need to retrieve entity in order to update attribute values

Scenario:
We have an existing account with a known GUID and would like to update their phone number.
Solution:

Common sense and traditional logic would often suggest to first open the specific account record, make modifications to all specific attributes, followed by update and close the entity:
ColumnSet cols = new ColumnSet();
cols.AddColumn("telephone1");
account myAccount = new account();
myAccount = oService.Retrieve(EntityName.account.ToString(), myAccountID, cols) as myAccount;
myAccount.telephone1 = "02 1234 1234";
oService.Update(myAccount);
The above code, though it works, contains a number of entirely unnecessary steps. For a far more efficient code block, see the following with an identical outcome:
account myAccount = new account();
myAccount.accountid = myAccountID;
myAccount.telephone1 = "02 1234 1234";
oService.Update(myAccount);
Note that there is no need to retrieve the targeted record before making modifications. As long as we set the entity ID to an existing GUID, the CRM SDK will take care of the rest. The stored value in the "telephone1" attribute will be replaced with the new value for the specified account GUID "myAccountID".

1 comment:

Anonymous said...

Hi Kiavash,

I had to make a slight change to the code fragment to get it working.

Key myAccountKey = new Key(myAccountID)

account myAccount = new account();
myAccount.accountid = myAccountKey;
myAccount.telephone1 = "02 1234 1234";
oService.Update(myAccount);


Phil