0

I am trying to wrap my head around the best way to approach this problem. I am importing a file that contains bunch of users so I created a handler called ImportUsersCommandHandler and my command is ImportUsersCommand that has List<User> as one of the parameters.

In the handler, for each user that I need to import I have to make sure that the UserType is valid, this is where the confusion comes in. I need to do a query against the database, to get list of all possible user types and than for each user I am importing, I want to verify that the user type id in the import matches one that is in the db.

I have 3 options.

  1. Create a query GetUserTypesQuery and get the rest of this and then pass it on to the ImportUsersCommand as a list and verify inside the command handler
  2. Call the GetUserTypesQuery from the command itself and not pass it (command calling another query)
  3. Do not create a GetUsersTypeQuery and just do the query results within the command (still a query but no query/handler involved)

I feel like all these are dirty solutions and not the correct way to apply CQRS.

Zoinky
  • 4,083
  • 11
  • 40
  • 78
  • I think the first option is a better solution. – Morilog Feb 02 '20 at 16:39
  • This SoftwareEngineering post might have some useful information in regards to that topic: [**How to validate command before executing on aggregate when validation needs to query data?**](https://softwareengineering.stackexchange.com/questions/380756/how-to-validate-command-before-executing-on-aggregate-when-validation-needs-to-q) – Nope Mar 03 '20 at 11:42

1 Answers1

0

I agree option 1 sounds the best but would maybe suggest adding a pre handler to validate your input?

So ImportUsersCommandHandler deals with importing you data (and only that) and add a handler that runs before that validates (in your example, checks the user types and maybe other stuff) and bails out of it does not pass. So it queries the db, checks the usertypes and does whatever it needs to if it fails. Otherwise it just passes down to your business handler (ImportUsersCommandHandler).

I am used to using Mediatr in NET Core and this pattern works well (this is what we do) so sorry if this does not fit with your environment/setup!

PaulD
  • 206
  • 1
  • 5