C# Code to retrieve lookup value id from target entity in D365 CE.

Let us consider below example as use case

We have Plugin that triggers on Update of Contact Table and wanted to retrieve Customer related to Contacts.

Customer is Lookup field on Contact Table.

Hence here our target entity is Contact.

Code –

 Entity targetEntity = (Entity)context.InputParameters["Target"];
  
 Guid ContactId = targetEntity.Id; 

Using the above code we get the target entity Contact Guid and now we need to retrieve Customer lookup from the target Entity.

var cols = new ColumnSet(new String[] { "parentcustomerid" });

Since we only want Customer lookup from Contact hence retrieving only Customer and you can retrieve columns as per your requirement.

Entity parententity = service.Retrieve("contact", targetEntity.Id, cols);

We have stored Retrieved values in parententity.

Guid ParentAccount = ((EntityReference)parententity.Attributes["parentcustomerid"]).Id;

And in above step we get the Guid of Customer.

Conclusion – This was simple example of accounts and Contacts, you can use the above code(specify the schema name of lookup field you want to retrieve) to retrieve any lookups from your target entity based on your requirement

Hope this helps !


Share Story :