web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Suggested Answer

Updating the field using C# plugin

(0) ShareShare
ReportReport
Posted on by 30

32755.png

The scenario is :

In SaleOrder entity , i take 'orderId'  and 'Potential Customer' Name and concat it in 'name' field of same record. it work fine for create operation but not work for update operation. i register both step in pre-operation. 

Adding code for reference

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"];
{

var OrderId = entity.Attributes["ordernumber"].ToString();
string OrderIdOriginal = entity.GetAttributeValue<string>("ordernumber");

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();
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"];
Entity entity = service.Retrieve("salesorder", context.PrimaryEntityId, new ColumnSet("ordernumber", "customerid"));
try
{

var OrderId = entity.Attributes["ordernumber"].ToString();
string OrderIdOriginal = entity.GetAttributeValue<string>("ordernumber");

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();

var concat = OrderId + " " + AccountName;

entity.Attributes.Add("name", concat );

}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}
}

pastedimage1684066065798v2.png

pastedimage1684066131154v3.png

it work fine for create operation but not work for update operation
I have the same question (0)
  • Suggested answer
    XM-22040801-0 Profile Picture
    11 on at

    Hi,

    Target contains only the modified fields.

    Target will be used by Dynamics to create/update your record in a pre-create/pre-update step: If you want to changes the data of the current record, do it in Target (like you do in Create message). In your code, you modify the record obtained by a retrieve, this record will not be updated by Dynamics.

    To avoid doing a retrieve (best practice), you can create a Pre-Image. Add the necessary fields (Order Number, Potential Customer) in the Pre-Image.

    To compute the name, look at the Target and Pre-Image. Example: If the user only change the Potential Customer, Target will not contains the Order number, so you need to get it from the Pre-Image.

    To learn more about Pre-Image: community.dynamics.com/.../pre-image-and-post-image-in-dynamics-crm

  • Ayush Solanki Profile Picture
    30 on at

    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 .

  • Suggested answer
    XM-22040801-0 Profile Picture
    11 on at

    In update operation, you need pre-operation and pre-image.

    In the pre-image, add customerid and ordernumber fields.

    Change your code in "update" by this:

    Entity entity = (Entity)context.InputParameters["Target"];
    
    try
    {
        Entity preImage = (Entity)context.PreEntityImages["Image"];
    
        // Take the orderNumber from the Target if it exists, otherwise take it from the PreImage
        string orderNumber = entity.GetAttributeValue("ordernumber") ?? preImage.GetAttributeValue("ordernumber");
    
        // Take the customerRef from the Target if it exists, otherwise take it from the PreImage
        EntityReference customerRef = entity.GetAttributeValue("customerid") ?? preImage.GetAttributeValue("customerid");
    
        // Retrieve Customer and get the name
        var customer = service.Retrieve(Customer.LogicalName, customerRef.Id, new ColumnSet("name"));
        string accountName = customer.GetAttributeValue("name");
    
        // Set the name of the order
        entity.SetAttributeValue("name", $"{orderId} {accountName}");
    }
    catch (Exception ex)
    {
        throw new InvalidPluginExecutionException(ex.Message);
    }

    This code take the target values first, if not exist it take the pre-image values.

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.

Helpful resources

Quick Links

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Congratulations to our 2025 Community Spotlights

Thanks to all of our 2025 Community Spotlight stars!

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Pallavi Phade Profile Picture

Pallavi Phade 102 Super User 2026 Season 1

#2
Abhilash Warrier Profile Picture

Abhilash Warrier 55 Super User 2026 Season 1

#3
ManoVerse Profile Picture

ManoVerse 51 Super User 2026 Season 1

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans