Transitioning to Event Sourcing, part 7: build a view model
Une version française de ce billet est disponible ici.
In this part, we are concentrating on the query part of CQRS. We will now be able to get views specifically for our pages, pre-calculated.
Your SQL tables for the views are now solely responsible for display. Please denormalize as much as you want. You are not constrained by the transactional model anymore, you just need to focus on a single responsibility. It means individual, simpler tables or documents. It means less entanglements (no more foreign keys needed!), and less dependencies. Your code and data model will become less complex, and thus more maintainable. It will probably speed up your team when implementing new features.
Usually, this step gets rid of much of the performance problems an application with a single shared data model usually experience. With a classical application, transactional behavior results in a very entangled normalized database. It means displaying a page in your application requires big, inefficient queries with lots of joins and other performance crippling SQL operations. With a view model specifically tailored for a given page, this problem disappear. You can now pre calculate your reports in real time (would that bring any business value?) just by handling the events.
Nothing! That is the cool thing about this step is that we already have a view model: the old entities persisted through our persisting event handlers. Our DTOs are already querying these tables. So no, this is not the most optimized view model, but it is still a perfectly valid starting point. For now, we are still using this model, so we can’t still modify it, but we can add views nonetheless. Actually, we could do that since we are persisting changes through the event handlers.
Running the sample
The sources for the entire series is available on GitHub at http://github.com/jletroui/TransitioningToEventSourcing
To run this sample, simply create a new “DDDPart6″ database in SQLExpress before launching it.
Last 3 steps of this series being very small and composable together, the single “part 6″ sample is actually covering parts 6 to 8.
Transitioning to Event Sourcing posts:
- Part 1: the DDD “light” application.
- Part 2: go CQRS with DTOs for the read side.
- Part 3: define commands explicitly.
- Part 4: track state changes.
- Part 5: use events for updating your domain database.
- Part 6: store events.
- Part 7: use events to build a view model.
- Part 8: remove the domain database, go event sourced.
- Part 9: a brief word on versioning, smart merging strategies, eventual consistency, scaling the read side, scaling the write side.