Using a Plugin to Generate Auto-Number Values for Legacy and Reopened Records in Dynamics 365 / Dataverse


In one of our recent Dynamics 365 / Dataverse projects, we ran into one issue with auto-number fields. We had configured an auto-number for the custom_id field on the Opportunity table. The format used a prefix of QU- followed by eight digits, resulting in IDs such as QU-00000133.

A screenshot of a computer

AI-generated content may be incorrect.

Everything functioned correctly for newly created records, and the field populated exactly as expected. However, during testing, we discovered a problem. When an Opportunity that had previously been closed was later reopened, the auto-number field did not populate as expected. The system did not treat the reopen action as a new record creation, so no auto-number was generated. Because the custom_id field was required for downstream integrations, the absence of a value became a breaking issue.

This happens because auto-numbers in Dataverse only trigger at creation time. A reopened record is simply updated, not recreated, so the auto-number mechanism never fires. This behavior is by design. Unfortunately, we had legacy records created long before auto-numbering was implemented, and when users reopened them for updates, those records still had no custom_id. The integration layer expects a value, so we needed a reliable way to populate one even after the original creation event had long passed.

To solve this, we implemented a plugin that checks whether the custom_id field is empty during update operations. If the value is missing, the plugin generates the next available QU number manually. The logic first retrieves the highest existing QU number in the system, extracts the numeric portion, increments it by one, and then applies the resulting value to the current record. Once the number is assigned, we also update the auto-number seed so that the built-in Dataverse auto-number engine continues from the correct sequence and avoids generating duplicates in the future.

The plugin was registered on the post update of the opportunity table with statecode, statuscode as the filtering attributes.

And PreImage with the following attributes – statecode, statuscode, custom_id.

A screenshot of a computer

AI-generated content may be incorrect.

Sample Code –

private void EnsureCustomId(Guid oppId, Entity preImage) 
{
    var customId = preImage.GetAttributeValue<string>("custom_id");
    if (!string.IsNullOrWhiteSpace(customId))
    {
        _trace.Trace("custom_id already populated, skipping.");
        return;
    }

    _trace.Trace("custom_id is NULL, generating new QU number.");

    var query = new QueryExpression("opportunity")
    {
        ColumnSet = new ColumnSet("custom_id"),
        Criteria =
        {
            Conditions =
            {
                new ConditionExpression("custom_id", ConditionOperator.NotNull),
                new ConditionExpression("custom_id", ConditionOperator.Like, "QU%")
            }
        },
        Orders =
        {
            new OrderExpression("custom_id", OrderType.Descending)
        },
        TopCount = 1
    };

    var existing = _service.RetrieveMultiple(query).Entities.FirstOrDefault();

    int next = 1;
    if (existing != null)
    {
        if (int.TryParse(existing.GetAttributeValue<string>("custom_id").Split('-').Last(), out int last))
            next = last + 1;
    }

    string newId = $"QU-{next:D8}";
    _trace.Trace($"Assigning new QU: {newId}");

    var update = new Entity("opportunity", oppId)
    {
        ["custom_id"] = newId
    };
    _service.Update(update);

    next = next + 1;

    var request = new OrganizationRequest("SetAutoNumberSeed");
    request["EntityName"] = "opportunity";
    request["AttributeName"] = "custom_id";
    request["Value"] = (long)next;
    _service.Execute(request);

    _trace.Trace($"Auto number seed updated to {next}");
}

Updating the auto-number seed is an important part of this solution. Without adjusting the seed, Dataverse might attempt to generate a number that has already been created manually by our plugin. By synchronizing the seed after each assignment, we ensure that the system’s internal auto-number feature continues counting from the correct position. This prevents duplicate values and keeps both manual and automatic generation aligned.

With this logic in place, reopened Opportunities now receive valid QU numbers automatically. The integration processes no longer break due to missing identifiers. Users can reopen and update older records confidently, and the system maintains a clean and consistent numbering sequence. A small enhancement to our plugin resolved a significant data quality issue end-to-end.

Hope it helps..


Discover more from Nishant Rana's Weblog

Subscribe to get the latest posts sent to your email.

Unknown's avatar

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

One thought on “Using a Plugin to Generate Auto-Number Values for Legacy and Reopened Records in Dynamics 365 / Dataverse”

Please share your thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Nishant Rana's Weblog

Subscribe now to keep reading and get access to the full archive.

Continue reading

Power Platform Puzzles

D365 CRM, Power Platform Tips &Tricks

Power Spark

Power Spark By Shrangarika

Van Carl Nguyen

Exploration of Power Platform

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog of Paul Andrew

Sponsored by Cloud Formations Ltd

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Microsoft Business Applications Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog - PPUG.ORG

AI - Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue

The Professional Paraphraser

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

Power Platform Learning

Your Go-To Resource for Power Apps, Power Automate & More

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.