Among multiple types of field attributes we can use inside CRM plugins, one particular we are going to excerpt is lookup field of type EntityReference. It is represented with three properties, Id as Guid of the entity record, LogicalName for logical name of the entity and Name for the value that can be described as textual feature of any entity record of type lookup.

While retrieving the value for the Name inside of the plugin, we need to be especially careful. This value can be null even though it exists and we retrieved the Id and LogicalName of that particular entity record. Now we are going to show you the way where Id and LogicalName were defined, but not the textual value itself.


if (context.InputParameters != null)
{
Entity entity = (Entity)context.InputParameters["Target"];
string institution = "";
string logName = "";


if (entity.Attributes.Contains("cs_institution"))
{
EntityReference instit = (EntityReference)entity.Attributes["cs_institution"];
institution = instit.Name;
logName = instit.LogicalName;
tracingService.Trace("Guid is: " + instit.Id + " , entity: " + logName + " value: " + institution);


}
entity.Attributes["cs_name"] = institution;
}

Inside of a Plug-In Trace Log on our CRM instance the following Message Block is visible.

PluginLookup

To retrieve the text value, i.e. Name of an EntityReference object, it was necessary to retrieve it from server. As we can see from MSDN on https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.entityreference.name.aspx:

“This property can contain a value or null. This property is not automatically populated unless the EntityReference object has been retrieved from the server. This value is used to provide text to represent the related record in any user interface elements, such as the value in a view column.”

The following lines of code inside PreCreate plugin for my custom entity retrieved the textual value for lookup attribute, where service is IOrganizationService variable.

protected void ExecutePreEducationCreate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}

IPluginExecutionContext context = localContext.PluginExecutionContext;
ITracingService tracingService = localContext.TracingService;
IOrganizationService service = localContext.OrganizationService;

if (context.InputParameters != null)
{

Entity entity = (Entity)context.InputParameters["Target"];
string institution = "";

if (entity.Attributes.Contains("cs_institution"))
{

var inst = ((EntityReference)(entity.Attributes["cs_institution"]));
var actualInst = service.Retrieve(inst.LogicalName, inst.Id, new ColumnSet(true));
institution = actualInst["cs_name"].ToString();
tracingService.Trace("Institution is " + institution);
}

entity.Attributes["cs_name"] = institution;
}
}