简体   繁体   中英

CQRS with multiple entities in EF

I have the following situation:

A State entity which is the root, it contains multiple parameters, most important are the URL and ID. I then have 3 entities which are optional to be connected to the State, but there always has to be 1 and can only be 1.

When sending the message(entity) to the command. Should i make 3 different commands for each option (which seems most likely to me), or should i send all entities even if some could be empty and figure it out in the command? Or is there another/better way to deal with this. As i'm used to have all data in 1 message, but i can't have that now.

CQRS does not dictate how you should divvy up the logic of a command (or query). There is nothing that inherently states you must separate this creation logic into several separate creation commands.

It is possible to implement CQRS on the BLL or on the DAL. This can influence the preferred approach. You didn't specify this so I can't judge it.

Generally speaking, when working with CQRS on the BLL, I scope my commands to a single transaction. If you need transactional safety between the State and its dependent (which sounds very likely in your case), stick to a single command.
If you don't need transactional safety, eg if you can defer the creation of the dependent to a later stage, then separate the two commands.

Note that even when working with a single command, you can still abstract each entity's creation logic to eg their own repository methods which will be called by the command handler (via its injected dependencies). This is perfectly fine. You don't need to route this via individual commands.

If your CQRS is implemented on the DAL, but the BLL manages the transaction (or you have no transaction), you can create separate DAL commands which the BLL service will trigger when needed. It makes no sense, however, to fire these commands blindly with possibly empty information which means nothing should be done. Only trigger a command when you know you need it to be executed. The BLL service should check if a dependent entity needs to be created, and only then should it trigger the respective command.

In all cases, the fact that only one dependent should be created for a State entity is business logic, and this should be implemented on the BLL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM