I've got Entity types that are in a parent-child relationship.
Since ExecuteTransactionRequest executes multiple message requests in one tranasaction, would the following work as I intend it to?
There are 3 parents with no children to start with:
//Create a 4th parent
cs_parent parent4 = new cs_parent{ cs_name = "p4" };
CreateRequest createParentRequest = new CreateRequest { Target = parent4 };
request.Requests.Add(createParentRequest);
EntityCollection parents 
  = context.RetrieveMultiple(/*fetchExpression to get all parents (I'm expecting 4 now)*/);
//Create a child for each parent
foreach (var p in parents.Entities)
{
  cs_child child = new cs_child
  {
    cs_parentid = p.ToEntityReference();
  }
  CreateRequest createChildRequest = new CreateRequest { Target = child };
  request.Requests.Add(createChildRequest);
}
response = (ExecuteTransactionResponse)context.Execute(request);
Would I be getting 4 parents with one child each then, or only 3 since when I'm retrieving multiple, the 4th one hasn't been created yet (?)?
If not, how do I revise my code ideally with still one Execute command at the end?
I haven't actually run your code for myself to be 100% sure, but it looks like it's going to error out because the fourth parent record doesn't have the necessary info on it at the time you assign it as an EntityReference on the child entity.  You can work around this easily though.  CRM allows for this type of situation where inter-dependent records can all be submitted within one batch Create request.  Normally when you create a record in CRM, the system assigns it a unique identifier (guid), but you can override this simply by assigning the guid yourself, then you have what you need to set it as a EntityReference on other objects.  So when you create the fourth parent, you would have something like this:
cs_parent parent4 = new cs_parent { cs_name = "p4",cs_parentId = Guid.NewGuid());
Just guessing at the Id field on your entity, but you get the idea.
One thing I'm not sure from your code sample, what context is, so I can't say for sure if doing a retrieve on that will return your parent4 object. You might need to have two loops, one for existing cs_parent records to create child records for them, and another loop to create child records for parent records in the request.Requests list that are not yet in the system... Food for thought.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With