CQRS: Refactoring Queries without Repositories

CQRS: Refactoring Queries without Repositories

This question posted on Twitter (and the subsequent thread) caught my attention. I had to pipe in with my own opinion on having queries without repositories.

To summarize, the question is about using Aggregate Roots with an ORM like Entity Framework. Should you eager load all navigation properties or alternatively I guess, use lazy loading?

My answer is if you’re only using an aggregate root for commands (to change state) and you generally have a higher read to write ratio, then eager load the navigation properties. As a general rule of thumb.

eShopOnWeb

I recently heard about eShipOnWeb from Steve Smith. It’s a reference application using ASP.NET Core 3.1 using a layered monolithic architecture.

I decided to take a look around and try and refactor a spot that was using a repository for a query.

There is a query to return all of the orders for a signed-in user. It’s pretty simple but is a good example of it using the OrderRepository along with a specification to fetch out the relevant orders. From there it creates a ViewModel that is used in a Razor view.

Here’s the razor view for reference

Looking at the Razor view, you can see that it doesn’t use some of the properties on OrderViewModel. The OrderItems or ShippingAddress properties are never used.

The Repository with the specification is retrieving the entire Order Aggregate Root and eager loading the OrderItems. We’re fetching in a lot of data that we simply aren’t using.

Refactoring Queries without Repositories

The refactor is rather simple. Just remove the repository and instead inject the Entity Framework DbContext (CatalogContext). The second part is creating a separate ViewModel (MyOrdersViewModel ) that only contains the data we need for our Razor view. Then use this new ViewModel as a projection in our EF Query.

Side Notes

In many situations, I prefer to create a SQL Database View that I will create a new class to represent and use that as a DbSet in my DbContext. And most often I have a completely different DbContext for writes vs reads. My Reads DbContext is what will have a model that represents the SQL view. This allows you to do that projection as an SQL View rather than doing the projection in your code.

If you were using a SQL Database View and created an OrderSummary class that was on your DbContext, that now might look like this:

Live Coding Session

I did a live coding session on my YouTube and Twitch channels. You can check out the recording here of doing this exact refactor.



GitHub

If you want to take a look a the full sample, you can also find my refactor changes on my fork of eShipOnWeb on GitHub.

Links

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.

Loosely Coupled Show: Software Architecture and Design

Loosely Coupled Show

I’m excited to announce the Loosely Coupled Show, a new project I’m working on with James Hickey. Check out the YouTube Channel and subscribe!

The premise is simple. To have discussions about software architecture and design. The target audience is intermediate to senior software developers.

Episode #000

We recorded a quick video to kind of describe what the plan is for the show, check out our “first” episode for more about the show and us and our backgrounds.

Loosely Coupled Show

I’ve also posted a short video on my CodeOpinion YouTube channel to elaborate a bit more on the announcement, which you can check out as well.

Software Architecture and Design

I think at no matter what level you are in terms of experience in software development, architecture and design are something you already do. To what degree is what varies.

From how you organize code, define dependencies and even naming. They’re all different aspects of design.

There are many more advanced topics we’d like to talk about such as:

  • Top-level Architectures
  • Event Driven Architecture
  • Domain Driven Design
  • Service Boundaries
  • Microservices
  • Messaging
  • Concurrency
  • Fault Tolerance

And we can’t leave out the cloud. Yes, it’s just someone else’s computer but it’s a real enabler for new ways to build and deploy applications.

If you have any recommendations for specific topics you would like us to cover, or to recommend a guest, let me know on Twitter or in the comments!

Related Links

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.

Roundup #68: Binding Redirects, Combining Types as Effects to Describe an Application, Endpoint from multiple middleware, Clean Architecture

Here are the things that caught my eye recently in .NET.  I’d love to hear what you found most interesting this week.  Let me know in the comments or on Twitter.

Binding Redirects

You’re probably here because of an error like this:

Could not load file or assembly ‘System.<…>, Version=4.x.x.x, Culture=neutral, PublicKeyToken=<…>’ or one of its dependencies. The system cannot find the file specified.

And you likely saw a build warning like this:

warning MSB3277: Found conflicts between different versions of “System.<…>” that could not be resolved.

Whelp, you’re not alone. We’re thinking about starting a survivors group.

If someone starts a survivors group, I’m joining. I’ve spent a serious amount of time and head-scratching over binding redirects. Specifically around System.Net.Http. The answer in my case was using <AutoGenerateBindingRedirects>

Link: https://nickcraver.com/blog/2020/02/11/binding-redirects/

Combining Types as Effects to Describe an Application

I can only imagine the face I made the first time someone referred to the type of an application. Coming from a Delphi, .NET, and web background at the time, I assumed the type of an application was Web vs Desktop vs Command Line. What I came to understand was that types can be used to model effects which can then determine what your application does.

Reid pointed out this post he wrote after I posted the following tweet (and my typo of “ton”… oops). I highly recommend reading this as Reid points out something I’ve never really thought of before.

Link: https://medium.com/@reidev275/combining-types-as-effects-to-describe-an-application-5830a1c48c05

Creating an endpoint from multiple middleware in ASP.NET Core 3.x

In a recent post I discussed the changes to routing that come in ASP.NET Core 3.0, and how you can convert a “terminal” middleware to the new “endpoint” design. One question I’ve received is whether that removes the need for “branching” the pipeline, and if not, how can you achieve the same thing with endpoints?

This short post assumes that you’ve already read my post on converting a terminal middleware to endpoint routing, so if you haven’t already, take a look at that one first! I give a quick recap below, but I won’t go into details.

Link: https://andrewlock.net/creating-an-endpoint-from-multiple-middleware-in-aspnetcore-3/

The Clean Architecture – Ian Cooper

What is the clean architecture and how you would build one in .NET? Recently Bob Martin has categorized a set of architectures, including hexagonal architecture, onion architecture and screaming architecture as ‘the clean architecture’ – a layered architecture of concentric circles with a strong emphasis on separation of concerns. This architecture has become popular because of its amenability to modification as an evolutionary architecture and its support for practices such as TDD. In this presentation we will discuss the clean architecture and its benefits. More than that, in the bulk of the presentation, we will show you how to implement a clean architecture in .NET. From first steps to working code, we will show you the moves required to embrace this approach, and introduce you to some of the OSS libraries that can help you get there. All examples will be in .NET Core

Link: https://www.youtube.com/watch?v=SxJPQ5qXisw

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.