How to add link to the parent of parent Datasource in QueryBuildDataSource?

Hi Everyone,

I am trying to convert the following query into QueryBuildDataSource :-

while select * from inventTrans

join inventDim

where inventTrans.inventDimId == inventDim.InventDimId

join inventBatch

where inventBatch.InventBatchId == inventDim.InventBatchId

&& inventBatch.itemId == inventTrans.ItemId

Like This :-

qbdsInventTrans = query.addDataSource(tableNum(InventTrans));

qbdsinventDim = qbdsInventTrans.addDataSource(tableNum(InventDim));
qbdsinventDim.relations(false);
qbdsinventDim.fetchMode(JoinMode::InnerJoin);
qbdsinventDim.addLink(fieldNum(InventTrans,inventDimId),fieldNum(InventDim,InventDimId));

qbdsInventBatch = qbdsinventDim.addDataSource(tableNum(InventBatch));
qbdsInventBatch.relations(false);
qbdsInventBatch.fetchMode(JoinMode::InnerJoin);
qbdsInventBatch.addLink(fieldNum(InventDim,inventBatchId),fieldNum(InventBatch,inventBatchId));
qbdsInventBatch.addLink(fieldNum(InventTrans,ItemId),fieldNum(InventBatch,itemId));

But in the line qbdsInventBatch.addLink(fieldNum(InventTrans,ItemId),fieldNum(InventBatch,itemId)) it is showing the exception " Invalid Field/Related field combination. "

How to resolve this ??

Thanks

Copying my reply from the same question in Dynamics Community forum:

Your code doesn’t do what you think.

The first parameter of addLink() is a field number of the immediate parent datasource, which is InventDim in this case. Therefore you’re adding a link to the field in InventDim table that that the same ID as ItemId field in InventTrans table. That’s clearly wrong.

Providing the datasource name in the third (optional) parameter should fix the problem.

qbdsInventBatch.addLink(fieldNum(InventTrans, ItemId), fieldNum(InventBatch, ItemId), qbdsInventTrans.name());

Thank Martin