The following C# plugin is used to fetch the record through relation and update contact records.
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
namespace XMA_ContactEntityUpdate_Plugin.XMA_ContactEntityUpdate
{
/// <summary>
/// PostOperationaccountUpdate Plugin.
/// </summary>
public class PostOperationaccountUpdate: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
//Initializing Service Context.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
try
{
//Defining Entity Object.
Entity eTarget = null;
if (context.MessageName == "Update")
{
eTarget = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] != null) ?
context.InputParameters["Target"] as Entity : null;
Guid accountIdGuid = eTarget.GetAttributeValue<Guid>("accountid");
QueryExpression query = new QueryExpression();
query.EntityName = "EntityName";
query.ColumnSet = new ColumnSet("columname");
Relationship relationship = new Relationship("relation_name");
relationship.PrimaryEntityRole = EntityRole.Referenced;
RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
relatedEntity.Add(relationship, query);
RetrieveRequest request = new RetrieveRequest();
request.RelatedEntitiesQuery = relatedEntity;
request.ColumnSet = new ColumnSet("name");
request.Target = new EntityReference("account", accountIdGuid);
RetrieveResponse response = (RetrieveResponse)service.Execute(request);
foreach (var industry in response.Entity.RelatedEntities[relationship].Entities)
{
var phone = industry["name"];
if (industryName != null)
{
QueryExpression qeContactUpdate = new QueryExpression("contact");
qeContactUpdate.ColumnSet.AddColumns("contactname");
FilterExpression filterUpdate = new FilterExpression(LogicalOperator.And);
filterUpdate.AddCondition("accountid", ConditionOperator.Equal, accountIdGuid);
qeContactUpdate.Criteria.AddFilter(filterUpdate);
EntityCollection entityCollectionUpdate = service.RetrieveMultiple(qeContactUpdate);
if (entityCollectionUpdate.Entities.Count > 0)
{
foreach (var entity in entityCollectionUpdate.Entities)
{
if (entity.Id != null)
{
Entity eContactUpdate = new Entity("contact");
eContactUpdate.Id = entity.Id;
eContactUpdate["phone"] = phone;
service.Update(eContactUpdate);
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
Regards,
Arun S Keerthi