title: CQRS Event Sourcing: Validate UserName uniqueness
body: <p>Let's take a simple "Account Registration" example, here is the flow:</p>
  
  <ul>
  <li>User visit website</li>
  <li>Click "Register" button and fill form, click "Save" button</li>
  <li>MVC Controller: Validate UserName uniqueness by reading from ReadModel </li>
  <li><strong>RegisterCommand: Validate UserName uniqueness again (here is the question)</strong></li>
  </ul>
  
  <p>Of course, we can validate UserName uniqueness by reading from ReadModel in MVC controller to improve performance and user experience. However, <strong>we still need to validate the uniqueness again in RegisterCommand</strong>, and obviously, we should NOT access ReadModel in Commands. </p>
  
  <p>If we do not use Event Sourcing, we can query the domain model, so that's no a problem. But if we're using Event Sourcing, we are not able to query domain model, so <strong>how can we validate UserName uniqueness in RegisterCommand?</strong> </p>
  
  <p><strong>Notice:</strong> User class has an Id property, and UserName is not the key property of User class. We can only get the domain object by Id when using event sourcing.</p>
  
  <p><strong>BTW:</strong> In the requirement, if the entered UserName is already taken, the website should show error message "Sorry, the user name XXX is not available" to the visitor. It's not acceptable to show a message, say, "We are creating your account, please wait, we will send the registration result to you via Email later", to the visitor.</p>
  
  <p>Any ideas? Many thanks!</p>
  
  <p><strong>[UPDATE]</strong></p>
  
  <p>A more complex example:</p>
  
  <p><strong>Requirement:</strong></p>
  
  <p>When placing an order, the system should check the client's ordering history, if he is a valuable client (if the client placed at least 10 orders per month in the last year, he is valuable), we make 10% off to the order.</p>
  
  <p><strong>Implementation:</strong></p>
  
  <p>We create PlaceOrderCommand, and in the command, we need to query the ordering history to see if the client is valuable. But how can we do that? We shouldn't access ReadModel in command! As Mikael <a href="https://stackoverflow.com/a/9496198/290617">said</a>, we can use compensating commands in the account registration example, but if we also use that in this ordering example, it would be too complex, and the code might be too difficult to maintain.</p>