Dynamics 365 CRM Save Multiple Entities in one Call with C# Early Bound Code.
Some time ago I showed a colleague how to save multiple related entities in early bound code. It's really simple once you know how.
The advantage of saving all entities in one save method is performance as only one round trip to the server occurs.
I believe under the covers the Save method of the CrmServiceContext (early bound context class) call is translated to a ExecuteMultipleRequest. I do not have the evidence to back this up, feel free to comment below confirming or correcting my assumption :).
I will demonstrates how to create an account, primary contact and a contact associated to the account in one save operation. The image below shows the final output of the code.
The first 26 lines of code create the account, primary contact and contact and associate them all together.
Lines 29, 30 and 31 add the new contacts and accounts to the context and the entities are created when save changes is called on line 33.
Lines 37 to 47 show how to check if an error occurred and how to retrieve the Guids of the newly created records, although this is not so important in the above sample as we explicitly set the id's of each entity with Guid.NewGuid(). The image below shows the console output with each entities Guid.
Be Careful and Take Note
It needs to be noted that while executing multiple operations in one save improves performance it can lead to unexpected behavior. The code above is not managed in a transaction therefore a number of the operations may succeed and a number may fail.
Removing the commented lines of code on lines 10 and 27 will result in the contact entity being invalid as the last name will be set to 2000 characters and will exceed the allowed max length, meaning the account and primary contact will be created successfully and the contact not being created.