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 :
Customer experience | Sales, Customer Insights,...
Suggested answer

Plugin errors while creating an entity and trying to increment the value of an attribute by default

(0) ShareShare
ReportReport
Posted on by 355

Hi,

I created a plugin which is triggered by a "Create" event and should assign a value to the "code" attribute by incrementing the code number of the last target entity created.
The code attribute is a whole number, and it's set as unique key.

When the plugin was triggered I got two different errors, this was the first one:

A record that has the attribute values Code already exists. The entity key Movie Code requires that this set of attributes contains unique values. Select unique values and try again.

The second one was a different business process error.

I downloaded both error log files and debugged in exception mode and realized that the last instructions have not be hit: could you please help me to understand if the issue depends on a wrong implementation? This is my Plugin code:

public void Execute(IServiceProvider serviceProvider)
        {
            var context = new PluginContext(serviceProvider);
            var service = context.CrmServiceSystem;
            var trace = context.TracingService;
            var target = context.GetTarget();

            var currentEntity = (Entity)context.InputParameters["Target"];

                          // query to retrieve all entities of the selected type:
            QueryExpression query = new QueryExpression("Target");
            query.ColumnSet = new ColumnSet("code");

                          // retrieve the last movie created:
            query.AddOrder("createdon", OrderType.Descending);
            query.TopCount = 1;
            var latestRecord = service.RetrieveMultiple(query).Entities.FirstOrDefault();

                          // retrieve the code of the retrieved entity
            var latestRecordCode = (int)latestRecord.Attributes["code"];

                          // increment the code by 1 and assign it to the current entity
            latestRecordCode++;
            currentEntity.Attributes["code"] = latestRecordCode;
        }

While debugging in exception mode, I realized that the variable latestRecord was given the correct value, but the instruction at line 23 ("latestRecordCode++") wasn't reached, I then changed the previous instruction as below:

Int32 latestRecordCode = Convert.ToInt32(latestRecord.Attributes["code"].ToString());

but I got a different issue: the instruction "latestRecordCode++;" is reached now, but the variable latestRecord is null.


Also, on the Plugin Registration Tool I looked for the profiles that should have been created when the plugin was triggered (instead than uploading the error log file) but I could not find any profile, are they supposed to be there?

I have the same question (0)
  • Suggested answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hello,

    Here are few recommendations:

    1. Add the check condition to your query that "code" field is not null.

    2. Use following code to get latestRecordCode:

    var latestRecordCode = latestRecord?.GetAttributeValue<int>("code");

    if there is latestRecord or "code" is blank - modified code will not throw an error but will get latestRecordCode to int.Default that is 0.

  • Joel D Profile Picture
    355 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hello,

    thank you for replying.

    I added the check condition as below (but I'm getting the same issues), did you mean the following?

    if(latestRecord.Attributes.Contains("code") != false)

    {
        (int)latestRecord.Attributes["code"];
        var latestRecordCode = latestRecord?.GetAttributeValue<int>("code");
        latestRecordCode++;
        currentEntity.Attributes["code"] = latestRecordCode;
    }
    else
    {
        throw new InvalidPluginExecutionException(OperationStatus.Failed, "The latest record was saved without a code");
    }

    Can you please explain to me the line of code you suggested:
    var latestRecordCode = latestRecord?.GetAttributeValue<int>("code");
    Is that "?" a ternary operator?

  • Suggested answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Regarding the check I thought of something like

    query.Criteria.AddCondition("code", ConditionOperator.NotNull);

    Regarding the "?" operator you can read here - docs.microsoft.com/.../member-access-operators

  • Suggested answer
    Manish Sonar Profile Picture
    40 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Joel,

    It seems service.RetrieveMultiple(query) is returning 0 entities in EntityCollection. Read "Code" field from "latestRecord" entity and set it in "latestRecordCode" if there is any entity retrieved from Query expression or else default value 0 will be used for "latestRecordCode". Your code should look like this:

    var latestRecordlist = service.RetrieveMultiple(query);

    int latestRecordCode = 0;

    if (latestRecordlist.Entities.Count > 0)

    {

       Entity latestRecord = latestRecord[0];

       if (latestRecord..Attributes.Contain("code"))

       {

           latestRecordCode = (int)latestRecord[0].Attributes["code"];

       }

    }

    // increment the code by 1 and assign it to the current entity

    currentEntity.Attributes["code"] = latestRecordCode++;

    Hope it helps.

  • Joel D Profile Picture
    355 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi,

    thank you for replying.

    Something anomalous happened when I triggered the plugin from another entity (the plugin is associated both to Movies and the Notebook entity): the first time I tried to save a new Notebook, it was saved successfully, but the code was given the value of the last Movie incremented by one (instead that of the last Notebook).

    The second time I tried to save another Notebook I got the same error as before, the first one ("A record that has the attribute values Code already exists...").

    The third time I got the other error, I then downloaded the error log file.

    While debugging in exception mode, the variable currentEntity is null (error CS0103: The name 'currentEntity' does not exist in the current context); the variable recordList is null too ("error CS0103: The name 'recordList' does not exist in the current context"). But the latestRecordCode has a value "9", which is equivalent to the code of the last Movie successfully saved (but I'm on the  Notebook  form, and the last code is 10)...

  • Manish Sonar Profile Picture
    40 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Joel,

    Can you post you updated code here?

  • Joel D Profile Picture
    355 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Manish, yes, sure:

    public class IncrementCode : IPlugin
    {
            public void Execute(IServiceProvider serviceProvider)
            {
                var context = new PluginContext(serviceProvider);
                var service = context.CrmServiceSystem;
                var trace = context.TracingService;
                var target = context.GetTarget();
    
                if (target == null)
                    return;
    
                Entity currentEntity = (Entity)context.InputParameters["Target"];
                QueryExpression query = new QueryExpression("Target");
                query.ColumnSet = new ColumnSet(true);
                query.Criteria.AddCondition("code", ConditionOperator.NotNull);
                query.AddOrder("createdon", OrderType.Descending);
                query.TopCount = 1;
    
                var recordList = service.RetrieveMultiple(query);
                int latestRecordCode = 0;
    
                if (recordList.Entities.Count > 0)
                {
                    Entity latestRecord = recordList[0];
                    if (latestRecord.Attributes.Contains("code") == true)
                    {
                        latestRecordCode = (int)latestRecord.Attributes["code"];
                        currentEntity.Attributes["code"] = latestRecordCode  ;
                    }
                }           
            }
    
    }

  • Manish Sonar Profile Picture
    40 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Joel,

    Can you try changing line number 14 to below:

    QueryExpression query = new QueryExpression(currentEntity.LogicalName);

    Please make sure that "code" is a logical name for respective field. Also as you said you are using same Code logic for for two different entities, in that case you might have to query both entities for max code and consider max from those two.

    In case  query expression still doesn't work you can try FetchExpression as a replacement. Refer below url:

    https://docs.microsoft.com/en-us/powerapps/developer/data-platform/use-fetchxml-construct-query

    Let me know if this solves your issue..

  • Joel D Profile Picture
    355 on at
    RE: Plugin errors while creating an entity and trying to increment the value of an attribute by default

    Hi Manish,

    thank you for your tips.

    I changed line 14 but got the same errors.

    Yes, "code" is the logical name ("Name" column, in the crm solution) for both entities.

    As regard to querying both entities for max code, I actually need the code of the last record of the target entity (and it's already supposed to be the max code) not the maximum value in absolute. For example, when the plugin is triggered by the Create operation of a movie, if the max code value from Movies is 10, the code of the new record will be 11. If I trigger the plugin while creating a collection, as the max code value from all the collections is 5, the code value of the new one will be 6.

  • CU26112055-0 Profile Picture
    2 on at
    Plugin errors while creating an entity and trying to increment the value of an attribute by default
    It sounds like your plugin is running into the classic issue where the create event fires before the record is fully committed, so pulling the last created entity can return nothing or an outdated value; you’ll want to make sure you’re querying in a secure, synchronous step and handling nulls properly, and if the URL you mentioned is supposed to help, I’d definitely check that it refers to the right table or filtering logic so the incremented code value is always based on the latest saved record

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 > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 186 Super User 2025 Season 2

#2
#ManoVerse Profile Picture

#ManoVerse 104

#3
Pallavi Phade Profile Picture

Pallavi Phade 61

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans