The code is:
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.IdentityModel.Metadata;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace CreateAndUpdate
{
public class OrderEntity : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
if (context.MessageName.ToLower() == "create")
{
Entity entity = (Entity)context.InputParameters["Target"];
try
{
var OrderId = entity.Attributes["ordernumber"].ToString();
EntityReference Customer = (EntityReference)entity.Attributes["customerid"];
//Retriving customer Name based on a ID
var RetrviName = service.Retrieve(Customer.LogicalName, Customer.Id, new ColumnSet("name"));
//Getting Customer Name
var AccountName = RetrviName["name"].ToString();
//myEntity.Id = entityId;
var concat = OrderId + " " + AccountName;
entity.Attributes.Add("name", concat);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
else if (context.MessageName.ToLower() == "update")
{
Entity entity = (Entity)context.InputParameters["Target"];
try
{
Entity postImageOrder = (Entity)context.PostEntityImages["Image"];
var OrderId = postImageOrder.Attributes["ordernumber"].ToString();
EntityReference Customer = (EntityReference)postImageOrder.Attributes["customerid"];
//Retriving customer Name based on a ID
var RetrviName = service.Retrieve(Customer.LogicalName, Customer.Id, new ColumnSet("name"));
//Getting Customer Name
var AccountName = RetrviName["name"].ToString();
var concat = OrderId + " " + AccountName;
entity.Attributes.Add("name", concat);
service.Update(entity);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}
}
Now it will get this error. "An item with the same key has already been added". when i update the record.
For update operation , I add post operation and post Image .