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:
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL
How can I create annotation(note) in account(Microsoft dynamics 365 crm) using plugin.