问题
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:
- Find the account by num (if it doesn't exist, I create them)
- Get the account = Account
- Create an opportunity with Opportunity["parentaccountid"] = Account;
- 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.
来源:https://stackoverflow.com/questions/50609263/error-account-with-id-xxxxxx-does-not-exist