Dynamics 365 Using EntityReference to Get Name from Id

Leave a comment

When connecting to Dynamics 365 from code, you can retrieve records of an entity through RetrieveMultiple.

When using RetrieveMultiple, you specify the columns you would like to retrieve using a ColumnSet. Either specify the columns like this:

ColumnSet columnSet = new ColumnSet("name", "opportunityid", "parentaccountid");

Or retrieve all columns like this:

 ColumnSet columnSet = new ColumnSet(true);

In some cases, the columns retrieved will be an Id. For example, when retrieving Opportunities, you have a parent account id. However, you may want to know the name instead of the id.

To get the name, you use an EntityReference without doing another lookup to the server. If we write some code to retrieve opportunities with the parent account id, you can see zooming over this entity record, the type is Microsoft.Xrm.Sdk.EntityReference. The field has several properties, including Name (e.g. “Humongous Insurance”):

From here, we can use the name instead of the Id. Complete code is below:

            try
            {
                var connectionString = @"AuthType = Office365; Url = https://yourinstance.crm.dynamics.com/;Username=user@test.com;Password=yourpassword";

                CrmServiceClient conn = new CrmServiceClient(connectionString);
                IOrganizationService service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

                EntityCollection entityCollection = new EntityCollection();
                ColumnSet columnSet = new ColumnSet("name", "opportunityid", "parentaccountid");
                var query = new QueryExpression
                {
                    ColumnSet = columnSet,
                    EntityName = "opportunity"
                };

                entityCollection = service.RetrieveMultiple(query);
                foreach (Entity entity in entityCollection.Entities)
                {
                    EntityReference account = (EntityReference)entity.Attributes["parentaccountid"];
                    string accountname = account.Name;
                    Console.WriteLine("Id: {0}, Name: {1}, Account: {2}", entity["opportunityid"].ToString(), entity["name"].ToString(), accountname);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }

This produces:

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, BI, Web, Cloud and Data Science.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

Your email address will not be published. Required fields are marked *