web
You’re offline. This is a read only version of the page.
close
Skip to main content
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
    RE: Updating the field using C# plugin

    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
    RE: Updating the field using C# plugin

    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
    RE: Updating the field using C# plugin

    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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Pallavi Phade – Community Spotlight

We are honored to recognize Pallavi Phade as our Community Spotlight honoree for…

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

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 72 Super User 2025 Season 2

#2
CA Neeraj Kumar Profile Picture

CA Neeraj Kumar 58

#3
Martin Dráb Profile Picture

Martin Dráb 54 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans