I want to fetch value from lookup field in plugin. Does anyone have code of it which can guide me how to do it. I am trying but stuck.
Thankyou
FYI.
public void Execute(IServiceProvider serviceProvider) { ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = factory.CreateOrganizationService(context.UserId); try { //step 1 Entity targetEntity = (Entity)context.InputParameters["Target"]; //step 2 get value EntityReference contactEr = targetEntity.GetAttributeValue("new_contact"); //step 3 set value Entity newEntity = new Entity(targetEntity.LogicalName); newEntity[""] = new EntityReference(contactEr.LogicalName, contactEr.Id); } catch (Exception e) { throw new InvalidPluginExecutionException(e.Message); } }
Hello Mukhan1833,
you can refer this code for Get Value of Lookup fields
EntityReference entref = (EntityReference)item.Attributes[attributeName]; var LookupId = entref.Id; var logicalName = entref.LogicalName; Set Value of Lookup fields newAccount[attributeName] = new EntityReference(logicalName, LookupId);Or you can refer this site for GET/SET of all datatype.https://www.crmcrate.com/plugin/how-to-read-and-write-values-in-different-fields-using-plugins/
EntityReference entref = (EntityReference)item.Attributes[attributeName]; var LookupId = entref.Id; var logicalName = entref.LogicalName; Set Value of Lookup fields newAccount[attributeName] = new EntityReference(logicalName, LookupId);
Hi mukhan1833,
Below is the sample code:
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName == "new_xyz") //entity logical name
{
if (entity.Attributes.Contains("new_abc")) //Lookup field logical name
EntityReference lookupObj = (EntityReference)entity.Attributes["new_abc"];
name = lookupObj.Name;
Guid id = lookupObj.Id;
}
Or you can use below link for refernece.
plugins - Get Value Dynamically from Lookup in CRM 365 using C# - Stack Overflow
Hope this will help.
Please mark as verified if the answer is helpful.
Thanks!
Vinit
Under review
Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.
As AI tools become more common, we’re introducing a Responsible AI Use…
We are honored to recognize Andrés Arias as our Community Spotlight honoree for…
These are the community rock stars!
Stay up to date on forum activity by subscribing.
DAnny3211 126
Daniyal Khaleel 117
Abhilash Warrier 70 Super User 2025 Season 2