I'm trying to copy lookup fields of a CRM to another CRM. But this fails because generally I got a exception saying that the attribute with the lookup logical name don't exist.
Ok I know that, because I'm trying to create it. When this occurs the referencing attribute of the relationship is the lookup, so the lookup must be in the referenced attribute.
But I try to search the relationship that have the lookup logical name in referenced attribute and I'm not finding, I tried the OneToMany and ManyToOne of both entities. So I need help to resolve this. Someone have a solution?
I don't want resolve this using solutions, because solutions cannot copy managed lookup fields. And I have all the attributes and entities to create in the another CRM, I only need to create the lookup and your relationship.
I have this basic code, but 2 CRMs is needed to test it.
public void CopyLookup() {
List<EntityMetadata> OriginEntities = new List<EntityMetadata>();
bool sucess = false;
while (!sucess) {
try {
RetrieveAllEntitiesRequest metaDataRequest = new RetrieveAllEntitiesRequest();
metaDataRequest.EntityFilters = EntityFilters.All;
// Execute the request.
RetrieveAllEntitiesResponse metaDataResponse = (RetrieveAllEntitiesResponse)Origin.IOrganizationService.Execute(metaDataRequest);
OriginEntities = new List<EntityMetadata>(metaDataResponse.EntityMetadata);
sucess = true;
return entitiesMetadata;
} catch (ThreadAbortException) {
} catch (Exception _ex) {
Console.WriteLine(String.Format("Fail to find Entities - {0}", _ex.Message));
if (_ex.Message.Contains("There was no endpoint"))
sucess = false;
else
throw new Exception(String.Format("Fail to find Entities - {0}", _ex.Message));
}
}
foreach (EntityMetadata ent in OriginEntities.Where(wh => wh.LogicalName.Contains('_'))) {
foreach (OneToManyRelationshipMetadata relation in ent.OneToManyRelationships) {
LookupAttributeMetadata lookup = (LookupAttributeMetadata)OriginEntities.Where(wh => relation.ReferencingEntity == wh.LogicalName).FirstOrDefault()
.Attributes.Where(wa => wa.AttributeType == AttributeTypeCode.Lookup && wa.LogicalName == relation.ReferencingAttribute).FirstOrDefault();
if (lookup == null)
continue;
CreateOneToManyRequest createOtm = new CreateOneToManyRequest() {
OneToManyRelationship = relation,
Lookup = lookup
};
bool sucess2 = false;
while (!sucess2) {
try {
Migration.IOrganizationService.Execute(createOtm);
} catch (EndpointNotFoundException) {
sucess2 = false;
} catch (TimeoutException) {
sucess2 = false;
} catch (FaultException ex) {
if (ex.Message.Contains("endpoint")) {
sucess2 = false;
} else if (ex.Message.Contains("there is already")) {
sucess2 = true;
} else {
sucess2 = true;
}
} catch (Exception ex) {
if (ex.Message.Contains("This could be due to the service endpoint binding")) {
sucess2 = false;
} else if (ex.Message.Contains("is not unique")) {
sucess2 = true;
} else {
sucess2 = true;
}
}
}
}
}
}