Error Account with Id = “xxxxxx” does not exist

2019-08-27 19:08发布

问题:

I have a custo workflow that creates an account and opportunities.

Sometimes I have this error: Account with Id = "xxxxxx" does not exist.

I don't know what's wrong in my code knowing that I find the account in the CRM.
Here are the steps of my plugin code:

  1. Find the account by num (if it doesn't exist, I create them)
  2. Get the account = Account
  3. Create an opportunity with Opportunity["parentaccountid"] = Account;
  4. Error message !

Code:

//Get opportunity
Guid id = retrieveOpportunity<string>("opportunity", "new_numero", numero, service);
Entity eOpportunity;
if (id != Guid.Empty)
{
    eOpportunity = new Entity("opportunity", id);
}
else
{
    eOpportunity = new Entity("opportunity");
}

//Get account
EntityReference eAccount = retrieveAccount<string>(accountCode, "account", "new_code", service);
if (eAccount == null)
{
    eAccount = new Entity("account", "new_code", accountCode);
    eAccount["name"] = "name";
    UpsertRequest usMessage = new UpsertRequest()
    {
        Target = eAccount
    };
    //create account
    UpsertResponse usResponse = (UpsertResponse)this._service.Execute(usMessage);
    eOpportunity["parentaccountid"] = usResponse.Target;
}
else
{
    eOpportunity["parentaccountid"] = eAccount;
}

UpsertRequest req = new UpsertRequest()
{
    Target = eOpportunity
}; 
//upsert opportunity
UpsertResponse resp = (UpsertResponse)service.Execute(req);

if (resp.RecordCreated)
    tracer.Trace("New opportunity");
else
    tracer.Trace("Opportunity updated");

Sometimes there are several workflows that are started at the same time and that do the same thing (creating other opportunities)

回答1:

You haven't shown us the entire plugin, so this is just a guess, but you're probably sharing your IOrganizationService at the class level, which is causing race conditions in your code, and one thread creates a new account in a different context, then its service gets overwritten by another thread, which is in a different database transaction that doesn't have the newly created account and it's erroring.

Don't share your IOrganziationService across threads!



回答2:

Whenever you are trying to consume the created record in the same transaction, convert the plugin into Asynchronous mode - this will work.