RE: Need to retrieve Related Entity Info using Plugin
Hi Kahspot,
My thought is that when the plugin executes in Customer context, we could retrieve Request entity records which has same parent customer record by QueryExpression class,
then get Request entity fields' information from retrieved result.
e.g: My demo is based on a default 1:N relationship: Account <-> Contact(parentcustomerid).
When I update an account record, retrive all associated contact records, populate description field of context entity with retrieved fullname and emailaddress.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Text;
namespace DynamicsPlugins
{
public class plugin2 : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IOrganizationServiceFactory servicefactory =
(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service =
servicefactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
// Make plugin only excutes for Account entity
if (entity.LogicalName != "account")
{
return;
}
// Prevent infinite loop
if (context.Depth > 1)
{
return;
}
try
{
QueryExpression query = new QueryExpression("contact");
query.ColumnSet = new ColumnSet("fullname", "emailaddress1");
query.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, entity.Id);
EntityCollection collection = service.RetrieveMultiple(query);
if (collection.Entities.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append("Associated contacts: \n");
foreach (var item in collection.Entities)
{
sb.Append("Name: " item.Attributes["fullname"] "\n");
if (item.Contains("emailaddress1") && !string.IsNullOrEmpty(item.GetAttributeValue("emailaddress1")))
{
sb.Append("Email: " item.Attributes["emailaddress1"] "\n");
}
}
Entity newEntity = new Entity("account");
newEntity.Id = entity.Id;
newEntity.Attributes["description"] = sb.ToString();
service.Update(newEntity);
}
}
catch (Exception ex)
{
tracingService.Trace("Error of Plugin: {0}", ex.ToString());
throw;
}
}
}
}
}
Register new step to run plugin:

Result:

You can replace entity name and fields parameter with your owns for test.
Regards,
Clofly