Get Related Entity name by passing entity and attribute name

Posted on Posted in CRM 2011 SDK, MS CRM 2011, MS Dynamics CRM

IN CRM 2011 SDK Get Related Entity name by passing entity and attribute name
private string GetRelatedEntityName(string orgname, string entityname, string attr)
{
try
{
using (OrganizationServiceProxy service = CrmServerConnection.GetOrganisationProxy(orgname))
{
//related entities start

QueryExpression qe = new QueryExpression(entityname);
qe.ColumnSet = new ColumnSet(true);

EntityCollection collection = service.RetrieveMultiple(qe);

Microsoft.Xrm.Sdk.Entity myEntity = collection[0];

//related

var relatedEntities = myEntity.RelatedEntities;
var relatedEntity = collection.Entities[0].Attributes[attr] as EntityReference;

var relatedEntityName = relatedEntity.LogicalName;

return relatedEntityName;
}
}
catch (Exception)
{
return “”;
}
}