How to reference @AggregateMember by id without knowing parent id

I have an Entity and EntityGroup as 2 separate aggregates. I need to be able to access Entity#id without knowing EntityGroup#id, so I can’t put Entity inside EntityGroup as an @AggregateMember because, in order to access an Entity, you have to provide both Entity#id and EntityGroup#id. Hence, I simply have Entity#groupId and EntityGroup#entityIds.

This is how I create an Entity: in an external non-aggregate class, I first check if there is a groupId provided, and if not, I send and wait for CreateEntityGroupCommand with random id, secondly, I send and wait for CreateEntityCommand with that groupId, then, inside @EventSourcingHandler of Entity, it sends and waits for AssignEntityToGroupCommand (which may throw “already exists”).

From this answer, I know that I should probably put AssignEntityToGroupCommand outside of the @EventSourcingHandler to not lock Entity but I feel like I have to, because if the entity already exists in the group then Entity must not be created.

It feels more natural to put this kind of validation inside the command handler of the Entity but then I would get that an Entity is assigned to Group before it was even created

Hi Sam,

An Aggregate Member in Axon terms is an Entity which belongs to an Aggregate Root.
The Aggregate description prescribes that there is “a single external reference point” towards an Aggregate.
This is the Aggregate Identifier, or in your question, the ‘parent id’.

Hence, if you want to target an Aggregate Member, you are required to also know the Aggregate (parent) id.
There is no way around this, and is by designed, due to the Domain-Driven Design description of an Aggregate.
This also relates to the workings of a Repository in Axon, for which you require provisioning an Aggregate Identifier, always.

From this answer, I know that I should probably put AssignEntityToGroupCommand outside of the @EventSourcingHandler to not lock Entity but I feel like I have to, because if the entity already exists in the group then Entity must not be created.

The logic to create or not create an Entity / Aggregate Member to me sounds like validation logic you perform on a Command Handler.
Thus, I’d model it as such, in the Command Handling function for the AssignEntityToGroupCommand.

Hope this helps out Sam, but I am not entirely sure.
Your question goes all over the place without a main line about what it is exactly which works or does not work.

Cheers,
Steven