The Read Model Facade

We’ve covered how we get data into our Read Model via our special Read Model Projections that use Entity Framework to insert View Model objects into a read-optimized SQL Server table. The table stores View Model objects in it, reducing the impedence mismatch we would run into if we didn’t have a separate Read Model. But how do we actually use the Read Model SQL Server?

Let’s not expose our DbContext to our Presentation Layer. Let’s design a service that is responsible solely for querying data and giving it to the Presentation Layer. To do this, we will use a Read Model Facade, best described by Dino Esposito in his series Introducing CQRS. The Read Model Facade is simply a wrapper around DbContext that restricts it to being read only:

public interface IRoastPlanningReadModel
    IQueryable<RoastScheduleViewModel> RoastSchedules { get; }

public class FakeRoastPlanningReadModel : DbContext, IRoastPlanningReadModel
    private readonly DbSet<RoastScheduleViewModel> _roastSchedules;

    // normally, we'd call constructor base(connectionString)
    // and _roastSchedules = base.Set<RoastSchedules>()
    // public FakeRoastPlanningReadModel() : base("RoastScheduleDb")
    // {
    //     _roastSchedules = base.Set<RoastSchedules>();
    // }

    // this constructor allows us to pass our
    // FakeDbSet used by IRoastPlanningDbContext
    public FakeRoastPlanningReadModel(FakeDbSet<RoastScheduleViewModel> roastSchedules)
        _roastSchedules = roastSchedules;
    public IQueryable<RoastScheduleViewModel> RoastSchedules => this._roastSchedules;

As far as exposing IQueryable<T> for drilling down and getting focused subsets of data from the database, I’m all for it. See my other post Exposing IQueryable in a CQRS Query Stack for more on that. But for now, we’re going to focus on how we use the Read Model Facade in the Presentation Layer, along side our Command Bus. Stay tuned!

continue reading…


I will be releasing most of this content only to subscribers. Make sure you sign up by clicking the big red button!

Related Posts:

comments powered by Disqus