Migrating Dynamics CRM entities from one organization to another is a matter of reading the source entity and using an insert/update step to create the destination entity with the same ID. If an entity references another 1:N it stores the ID of that entity in one of its fields.
As long as you create the referenced entity first and copy the id fields, the relationships are intact.
What if you have N:N relationships ?
In this case neither entity stores the id of the other. A third entity called an Intersect Entity contains the id of both entities and forms a bridge between the two.
Once you create both entities involved in the N:N relationship you need to create an instance of the intersect entity to form the relationship.
For the example of account and lead there is a N:N accountleads_association that uses an intersect entity called accountleads.
The accountleads entity has a field for accountid and leadid.
The UI shows both of these fields as read-only. When you map values to these fields you will get a warning that the step may fail. You can ignore this, as long as both referenced entities exist, the relationship will be created.
You can use a Create step but not an Insert/Update or Update step with intersect entities.
You should consider a lookup to skip the create step if the entity already exists. If the entity already exists, you will get an error about a duplicate key insertion.
The lookup uses the accountleadid to match the target.
The If statement checks the lookup result and executes the Create if the entity was not found.
Thanks to Brenden Peterson at Scribe Software for his input. The warnings when you try to map the fields were causing me some concern, but they can be safely ignored.
The same process that works for the account to lead N:N works with custom entities as well.