D365FO: Safe pattern for fetching/updating records across companies in X++ without using wrong execution context
In D365 Finance & Operations (X++), what is a reliable pattern to fetch and update records across legal entities using crossCompany/crossCompany::find vs changecompany, while preventing accidental reads/writes to the wrong company or recursion/side effects?
Context:
- Code runs in a multi-company environment and sometimes is called from processes that may already be executing under a specific company.
- We need to retrieve a record from another company (e.g., based on a
CompanyIdfield), process it, and write back. - We want to avoid:
changecompanywrapping causing nested/company-mismatched execution (recursion or unexpected company context).crossCompanyselects returning data from an unintended context.
Questions:
- When should we prefer
crossCompany/crossCompany::findoverchangecompanyfor reads vs updates? - How can we validate/lock the intended
dataAreaId(e.g., asserting current company context, usingCompanyIdpassed in, or restoring context) before executingselect/update_record? - What sample X++ structure would you recommend (method boundaries, scoping, and
companyIdhandling) to make it safe and testable?
1 answer
Write an answerReliable pattern for cross-company read/update (without wrong execution context)#
Key idea#
In D365FO, company context is part of execution. changecompany changes the execution context (and therefore what the runtime considers the “current” company for buffers/records). crossCompany does not mean “run this block under another company”; it’s mainly a way to address a specific company for a read and/or to make intent explicit.
A safe pattern is:
- Compute the target
dataAreaIdexplicitly from input. - For reads: use
crossCompany/crossCompany::find-style addressing with the explicit target company. - For writes: do the write in an isolated scope that explicitly switches to the target company once, validates preconditions, and avoids nested recursion.
- Do not keep record buffers from one company and write them in another.
- Avoid nested
changecompanyby isolating the write in a dedicated method and ensuring callers don’t already wrap.
1) When to prefer crossCompany vs changecompany#
Prefer crossCompany / crossCompany::find for reads#
Use cross-company addressing when:
- You only need to read data from a known other company.
- You want the code to state the target company in one place.
Why:
- It reduces the chance you’ll accidentally
selectunder the wrongdataAreaId. - It makes it easier to review/test because the target company is explicit.
Limit: crossCompany is not a universal replacement for writes. For updates, you still need to ensure the record is updated under the correct company execution context.
Prefer changecompany for updates (but isolate it)#
Use changecompany when:
- You need to update the record and therefore must execute in the correct company context.
- You want to guarantee that
doUpdate()/update()/ttswork under the intended company.
Why:
- The runtime must execute the persistence logic under the correct
dataAreaId.
But: Use it carefully to avoid nesting.
2) Validating/locking the intended dataAreaId#
You generally want two checks:
A) Validate input consistency#
- Ensure the method was given a valid
targetCompanyId. - Ensure it is not empty and is not equal to an unexpected value.
B) Ensure you don’t “lose” the context accidentally#
Common safety tactics:
- Capture the caller context (current company) and restore it in a
finallyblock (if you do any context switching). - Keep company switching at a single boundary (one method that performs the
changecompany).
Note: In X++, the idiomatic “safe” approach is to isolate switching rather than trying to micro-manage every
select. That’s where most bugs come from.
3) Sample safe and testable structure#
Below is a template pattern. Since you didn’t specify the table, field names, or business rules, the example uses placeholders:
MyTablewith a key fieldRecIdand aCompanyIdcolumn.- We read a record from
targetCompanyIdand then write back under that same company.
Recommended method boundaries#
processForCompanies(...)(no company switching): orchestrates.readInCompany(targetCompanyId, key)(no execution switching for reads): uses cross-company find/select.updateInCompany(targetCompanyId, recId, newValues...)(singlechangecompanyboundary): validates, locks, updates.
Example X++ template#
public void processForCompanies(MyCompanyId targetCompanyId, RecId sourceRecId)
{
// Orchestrator: no changecompany here.
// Validate early.
if (!targetCompanyId)
{
throw error(strFmt("Target companyId is empty."));
}
// Read the record from the target company explicitly.
MyTable sourceRec = this.readInCompany(targetCompanyId, sourceRecId);
if (!sourceRec)
{
throw error(strFmt("Record not found in company %1.", targetCompanyId));
}
// Apply business logic on a detached copy.
// IMPORTANT: do not attempt to update this buffer outside the target company.
MyTable updatedRec = sourceRec;
updatedRec.SomeField = "NewValue"; // placeholder business logic
// Write back under the target company only.
this.updateInCompany(targetCompanyId, updatedRec);
}
private MyTable readInCompany(MyCompanyId targetCompanyId, RecId recId)
{
MyTable t;
// Prefer explicit cross-company find for reads.
// (Pattern equivalent to crossCompany::find)
t = crossCompany(MyCompanyId::findDataAreaId(targetCompanyId))
.find(recId); // or: select crossCompany ... where ...
return t;
}
private void updateInCompany(MyCompanyId targetCompanyId, MyTable updatedRec)
{
// Validate that the buffer belongs to what we think it belongs to (optional but helpful).
// If you have a CompanyId column, assert it matches.
if (updatedRec.CompanyId != targetCompanyId)
{
throw error(strFmt(
"Company mismatch. Buffer company %1, expected %2.",
updatedRec.CompanyId, targetCompanyId));
}
// Isolated company switching for update.
ttsbegin;
changecompany (targetCompanyId)
{
// Re-fetch inside the company context to avoid updating a cross-company buffer.
// This also allows locking and ensures correct tenant context.
MyTable locked;
select firstOnly forUpdate locked
where locked.RecId == updatedRec.RecId;
if (!locked)
{
ttsabort;
throw error(strFmt("Record disappeared in company %1.", targetCompanyId));
}
// Apply changes.
locked.SomeField = updatedRec.SomeField;
locked.doUpdate();
}
ttscommit;
}Why this works#
- Read is explicit:
readInCompany(...)addresses the target company for thefind/select. - Update is isolated:
updateInCompany(...)uses exactly onechangecompanyboundary. - Re-fetch inside update: ensures the record is loaded/locked in the correct company context and avoids “buffer from wrong company being updated”.
forUpdate+doUpdatereduces race conditions.
Edge cases / gotchas to watch#
- Nested
changecompany: If upstream code already useschangecompany, nesting can cause hard-to-debug outcomes.- Mitigation: keep all switching in one place (the
updateInCompanyboundary) and document that callers must not wrap again. - If you suspect nesting from orchestration (batch/async handlers), involve human review to decide whether to detect and short-circuit.
- Mitigation: keep all switching in one place (the
- Updating a buffer that was read cross-company: Don’t do
updatedRec.doUpdate()outside the correct context.- Mitigation: always re-fetch inside
changecompany.
- Mitigation: always re-fetch inside
- CompanyId column vs RecId uniqueness:
RecIdis typically unique within a database context; but your safest check is still validating the company identity using your explicittargetCompanyIdand (if available) the record’sCompanyId.
- Transactions across companies:
- The sample wraps
ttsbegin/commitaround thechangecompanyblock. - If your business requires multiple companies in one transaction, you must consider whether the data model/business logic allows it. If not, split by company and commit per company.
- The sample wraps
- Performance:
- Avoid cross-company loops with per-row
crossCompanyselects. Prefer bulk operations (where possible) or limit cross-company reads. - Re-fetching for updates is correct but can be expensive; keep it only for rows you truly update.
- Avoid cross-company loops with per-row
Answers to your questions (direct)#
- Prefer
crossCompanyfor reads when you need to fetch records from a specific other company and want to keep the current execution context stable.
Prefer changecompany for updates, but isolate it into a dedicated method and re-fetch inside that method.
- Validate
dataAreaIdby:- Checking it’s not empty/invalid.
- Asserting it matches the record’s
CompanyId(if you have that column). - Keeping company switching only inside the update method, where you can guarantee the correct context.
- Use
forUpdateto lock and reduce races.
- Recommended structure:
- Orchestrator method does business logic and passes
targetCompanyIdexplicitly. readInCompany(...)usescrossCompanyaddressing.updateInCompany(...)is the only place usingchangecompany; it validates, re-fetches, locks, and updates.
- Orchestrator method does business logic and passes
If you share the specific table + how you identify the target company (e.g., CompanyId field name and key structure), I can adjust the template to a more concrete select/find pattern and show how to bulk-read safely without per-row cross-company overhead.
Know the solution?
Sign in to contribute an answer and build your community reputation.
Sign in to answer