Domain Models in presentation frameworks

One common question when applying DDD is how to interpret other architecture’s concepts of a “model”.  For example, two common presentation architectures are MVC and MVP.  In each of those acronyms, the “M” is short for “Model”.  So what exactly is this Model?  Is it the Domain Model?  Presentation Model?  Something else entirely?

This question came up recently on the DDD list, and naturally, a slew of wide ranging answers came pouring in.  One of the problems with trying to marry these two concepts is that MVC is a rather old concept, with roots almost 30 years old now.  The concept of a “domain model” certainly wasn’t invented by Eric Evans.  However, it takes some sleuthing to understand if the DDD model concept applies to MVC.  It’s rather clear that the original concept intended that the “M” is “domain model”.  Randy Stafford pointed this out in one of the replies to the original question, also suggesting an alternative name to the separate Model concept, “Model Model View Controller”.  Another is the concept of “Model View ViewModel”.

Personally, I don’t like either of these names.  Rather than come up with a different name, the real question comes down to, “should I use my Domain Model as my Presentation Model?”  Lately, I’ve leaned strongly towards NO.

Keeping our POCOs safe

When programming in an MVC architecture, you’re often playing by someone else’s rules.  We strive to make our entities POCOs (Plain Ol’ CLR Objects), and completely persistent ignorant.  Just as the persistence layer is an infrastructure detail, the View and Controller technology are a similar type of infrastructure, just at the other end of the pipeline.  If we create our POCOs, then expect them to be used in the Controller and View (especially as things like arguments to a controller action), limitations on the technologies make our objects look like all sorts of crazy.

Now, no one really suggested making entities as arguments to controller actions, as the MVC technology can’t support the richness of our POCO objects.  But what about the model passed to the View?  Still, because of the limitations of MVC technology, the Model used in a View must look a very certain way for binding to work correctly.  For example, in MonoRail and ASP.NET MVC, collections usually need to be arrays, and properties need to be read-write for binding to hook up properly.  The same holds in MVP architectures, where the View technology is very sophisticated, but needs a Model that “plays nice” with its expectations.  Otherwise, you won’t get any of the benefit of the underlying technology.

But we don’t want our entities to be sullied by these outside forces.  We want to create rich models, untouched by persistence and presentation concerns.  But to take full advantage of our presentation/view frameworks, we have to create something else.  That “something else” goes by a couple names, both “ViewModel” and “Presentation Model”.  I really like this concept, not only because of my zealotry for POCOs and DDD, but because it’s a natural manifestation of the Separation of Concerns principle.

Separating our presentation concerns

In addition to presentation/view frameworks requiring their models to look a very certain way, often many concepts belong only in the presentation layer.  Things like required fields, type checking, and other invariants are a product of the task of interpreting user input.  Since all data comes as text over the web, something has to translate these values to types like ints, decimals, enumerations, and so on.  Presentation frameworks can go quite a long way to convert types, but what about non-trivial cases?

What about the web form that has an input for Hour and Minute, and you need to combine them?  But “Hour” needs to be a real hour, not 5784.  That rule has no business in the Domain Model, as my model cares about DateTime, not about individual Hour Minute values.

For things like invariants and validation, I don’t want my Domain Model stuffed with invalid values that I then have to check after the fact.  But stuff a ViewModel with invalid data, no harm done.  I can validate that object by itself, and report the errors back to the user in a way that most presentation frameworks have built-in support for.  It’s clear that while we’d have to make sacrifices in our Domain Model to make it available in the view, it’s often advantageous to simply break free altogether and embrace a completely separate ViewModel.

Crafting a wicked ViewModel

When crafting a ViewModel in MVC land, there are two main “models” you need to worry about: the ViewModel used by your View, and the ViewModel used in action parameters.  When designing a GET ViewModel, I craft the ViewModel to contain only what is needed by the View to display its data, and nothing more.  Some folks call these DTOs, some ViewModel, but the idea is that you don’t pass your entities to the View.  Create some ViewModel, map your entity to it somehow, and pass the ViewModel to the View.  In our current project, we’re using a fluent-y auto-mapped solution, so that we never need to configure our mapping from Domain Model to ViewModel (this should be in MVCContrib sometime soon).  The nice thing about this ViewModel is that it can use things like MVC validation and binding technologies, gelling nicely with whatever View framework you’re using.

In the action parameter side, here it really depends if the request is GET or POST.  For POST, I have only one action parameter, and this is the same ViewModel type that was used to construct the original form.  For GET, my rules are relaxed, and I might use Controller technology to bind actual entities to the parameters, so that I don’t have to manually load them up myself.  In any case, I make a hard distinction between what my Controller uses, and what my View uses.  I have no issue with the Controller knowing about my entities.  But when it comes to the View, it’s generally best to let the presentation/view technology do what it does best and not affect my POCOs.

One nice side effect of this approach is that you can design your ViewModel exactly around each screen, so that one entity could be used on several screens, but you’d never need to compromise on the design of each individual ViewModel.  Since each View has its own ViewModel, no other View influences the data it displays.  Separation of Concerns circling around again.

Keeping it simple

If you’re in a domain where your domain model can be easily used in your Views, you should take a real, hard look at other ways of making your life easier like the Active Record pattern.  But if you’re having trouble dealing with DDD, it often comes with the impedance mismatch between MVC technologies and the quest for POCOs.  You’re not doing anything wrong, except trying to force that elegant square peg into that stubborn round hole.  By letting MVC frameworks do what they do best, and use mapping to go between these layers, we can shield our model from the concerns of the presentation layer.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in ASPNETMVC, DomainDrivenDesign, Patterns. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Artur Trosin

    Thank you very nice article, but still what does the M means for MVP pattern from your perspective, where the M is completely disconnected from the View?
    In MVP, the View doesn’t have access to Model (directly), and Presenter sets all View data by exposed View interface.
    From my point of view the M – could be fully DM in this case, or…?
    Thank you

  • Nice post Jimmy. Considering adding another Model makes me a bit uncomfortable. That said, I can appreciate the mismatch, and how Model ViewModel could clean things up a bit.

    The most time-consuming part could be mapping from Model to ViewModel. Sounds like you’ve got this sorted! Would be great to see some code – any idea when a preview will be in MVC Contrib?

  • lubos

    “What about the web form that has an input for Hour and Minute, and you need to combine them? But “Hour” needs to be a real hour, not 5784. That rule has no business in the Domain Model, as my model cares about DateTime, not about individual Hour Minute values.”

    Why your example model cares about DateTime? Why it can’t have Hour and Minute fields directly in the model? That’s what users see after all when they enter data and that’s what they get when they view/edit data, right? Why use DateTime at all then? Because it’s more efficient? That’s infrastructure detail. You said it there… “your model should be completely persistent ignorant”

    I’m kind of leaning more to the idea of having domain model act as presentation model instead of creating some kind of ViewModel. I would like to move on but there are (as of now) no strong arguments for either side.

  • David McClelland

    I believe this is referred to as the Presentation Model pattern by Martin Fowler, and Jeremy Miller has a good write-up about it as well.

  • Hi Jimmy,

    Very interesting topic, I do have one question. When you’re stating that presentation validation should be on the presentation model I’m wondering what happens if you have validation that must occur in the domain model. For example a required field in your domain model. You’ll want to validate this in your domain model and you’ll need to validate it in the presentation model to present validation errors to your end user.

    Are you going to write the same validation twice? In the presentation model and in the domain model?

    I can’t really get my head around how you could solve this without having code duplication.

  • Another pattern that seperates view model concerns from that of your domain model is the Presenter-First pattern.

  • @Artur

    MVP is a little different than MVC as you pointed out. However, you’re more likely to go fully MVVM, where the View has its own “Model” that takes advantage of databinding features, for example. I’m going to have to point to Jeremy Miller’s CAB articles for more info, I don’t have that much experience in MVP-appropriate apps like WinForms.

  • @Peter

    We try to make a clear distinction between invariants and constraints. Constraints can be enforced anywhere, at the database level, in our domain, or in our presentation layer. We try to enforce constraints _Before_ it hits our domain model simply because it’s easier to deal with constraint violations at the point of input, at the database or at the UI level.

    But we do have invariants, like “ArrivalDate must be in the future”. Since these are based around operations, we can supply the results of an operation on the domain object itself. Our operations that modify our domain model can return a “result” object that has success indicators and a list of failure reasons. We can then bubble that back up however we want.

  • @lubos

    There’s a difference between how a user _inputs_ data versus how we model it. When we display this information, for example, it’s in one big DateTime field. They just like to input it the dates in this particular way. If the UI team decides on a different way to input Dates and Times, this shouldn’t affect our model.

    Not only do I want persistence ignorance, I want complete Infrastructure Ignorance, where the model is not influenced by my MVC nor persistence technology. In our case, we went to ViewModel out of necessity – the View was causing us to change the design of our model. This is something we didn’t want to allow.

    Going straight to ViewModel simply leaves these problems in the dust. By separating those concerns, I don’t have to worry about the possibility of a design compromise in my model.

  • Kerry

    You did a really good job at describing a problem that many of us have dealt with. Our solution has been to put a DTO in as a seam between the View and the Presenter – not too terribly different from the “ViewModel”, especially insofar as things like translation logic (Hour, Minute, &etc.) are left in the DTO.

    One mistake I made recently was to the DTO interface implement the View directly – that created lots of unnecessary interface methods in the view.

    Thanks for the direction here – an extra layer may seem cumbersome at first, but I think it might go a long way towards removing the burden that goes with trying to force a pattern.

  • Rob

    Great article. Now that I have built several Monorail/MVC applications and several large WPF applications, I can look back and see that every time we merged our presentation model with some other model “type” (either domain model or communications model) we had a mess on our hands and ended up with a less feature rich user interface too. It takes a little extra work in the beginning to put these two different models in place, but it is well worth the effort.

  • @bogardj

    Hmm, don’t you have to check constraints at both the presentation model and the domain model? Isn’t it a problem if you only check constraints of your domain model in the presentation model?

    If you’re domain model can return results, how do you exactly let it bubble up? Is that going through your presentation model?

  • lubos


    But if we assume that UI team is not completely stupid and if they think that Date and Time input should be separated for end-user, why should it be combined in our model? Because our language provides convenient DateTime struct? That’s hardly “infrastructure ignorance”.

    Models are very abstract and subjective area. If you can’t prove that using DateTime struct is better than having two fields for date and time in my model, I will always err on side of being consistent with UI. If I’m lucky, then I might even end up with model that can map 1:1 to presentation layer.

    My point is that model can be adjusted to reflect requirements from UI or persistence layer as long as programmer doesn’t feel that he makes compromises in design or breaking SoC. because models are so abstract and subjective, there is usually plenty of maneuver space for many design options being all equally correct. If some options make it easier for view or persistence layer, why not take advantage of them?

    Anyway, If I change my mind about all this, I’ll let you know :-) I just need more experience.

  • @Peter

    We check constraints and the presentation layer (not necessarily in the model object). We try to put as much constraint checking in the ViewModel, through techniques like Castle Validator, etc.

    Invariant checking, or “business rules”, is preferable to happen at least in the domain layer, if not the domain model itself. We bubble up through a “results” object, that our controller can then check to perform its additional logic.

  • @lubos

    But the deal is, the separate date/time doesn’t show up in our model. It shows up only in editing, and not in viewing (this is just our one specific case).

    For our MVC frameworks we use, we’d have to make significant changes to make them work easily with the binding logic. Instead, we’ll let the domain take care of interpreting form objects/messages, and let the presentation layer be in charge of displaying a simple DTO/ViewModel object.

    It doesn’t really apply to all models or frameworks. Rails, for example, the Model _is_ a “domain model” (but implemented w/ Active Record). But as presentation technology gets more complex, I don’t want those persuading my model to look a certain way.

  • Thanks for making a murky subject so clear Jimmy! One thing I think is worth calling out is that lots of apps don’t need the extra complexity of a view model and a domain model (simple data entry apps for instance). In these cases, some kind of active record implementation might be all you need.

  • I have taken the ViewModel concept even further again by having a DTO for taking the information to the view and another DTO that brings information back to the controller.

    It certainly seems like overkill in the first instance but is quite manageable with a robust mapping infrastructure. On the project I was working on our biggest problem was not having clear conversations about what was responsible for what. To fix that I created the language of VTO (view transfer object – takes information to the view) and DTO (domain transfer object – takes information towards the domain).

    I know this is ‘SRP to the max’ but it has some definite benefits particularly around testability and also in terms of functionality. In the date time example discussed earlier the VTO would carry information to the screen as a string pre-formatted for display according to any presentation rules you may have for date time values. Then after the post action the controller accepts a DTO as its only parameter (leveraging custom binders) where the value is parsed and carried as a DateTime value.

    I would be interested to hear others thoughts.

  • @Steve

    Nope, that’s _exactly_ what we’re doing. Except we call them “DTO” and “…” … FormModel? One is optimized for displaying, and one is optimized for capturing. Because we’re using auto-mapping from our Domain Model to both of these guys (for edit scenarios, for example), we don’t have to do that boring mapping code.

    And exactly how you have your scenario, each xTO carries _exactly_ what is needed, and no more.

  • @jimmy, @Steve (the other one… not myself),
    re: the two different “view models” used for a) going to the view, b) coming back from the thew to the controller. I think Chad Myers, Jeremy Miller, & Co. call them a) ViewModel and b) EditModel.

    I’m not sure thats any clearer, but I think the important thing is to use two separate models, name them as you see fit, and then use those names consistently.

  • Jimmy,

    great post :-) Really insightful.

    Would be really nice to get some pointers on your “automapping” stuff, do you use code-gen or some expression tree thing? Would love a blog post on the general concept. Been thinking about that lately.

    - Rasmus.

  • Dimitris Menounos

    I have to dissagree. From my experience, in a project with a couple of hundrend model classes where we use DTOs for the view, I think that they are 90+% pure code duplication and a *terrible mess* to maintain.

    In my personal projects I use the model directly up to the view and grass is alot greener!

  • Great post! It gives a very concrete and detailed perspective on these problems.

    Two things strike me:

    In my experience, a View model that completely hides the Domain model will cause a lot of duplicate code. To me this means you have to have a good strategy for “auto mapping”. Without it there is just way too much overhead. This is a topic you mention but do not go into details with. Some details here would be highly appreciated.

    Is your approach (including your “auto mapping” strategy) based on a 1:1 mapping between domain model and presentation model? My experience with this is that the presentation model will sometimes contain information from several domain models. What is your take on this problem?

    - Tore Vestues

  • @Dimitris

    Before we had a good mapping strategy, I would have agreed. Testing manual mapping code is tedious to the point of hair-pulling. Definitely not every model needs this strategy. But when we put it in, we were quite surprised how much the presentation technology influenced our designs. For the projects where domain model is not 1:1 with screens, this strategy definitely helps.

  • @Tore

    Short answer: yes we have a strategy for bringing multiple entities together.

    Honestly, 95% of the time, if the models are shown on one screen, they likely have a relationship built in already. If not, we take a hard look at putting it in.

    If there are multiple disparate entities in one screen, we look at several things:

    - Is each entity related to one section, a widget, that should be made into a partial/subcontroller/partial request/RenderAction call? If so, we break it out that way
    - If not, create a component that combines all the models. This component likely has some concept in the ubiquitous language, so we often put that component type in our domain.

  • Great post. Have you ever posted more details on your auto-mapping thing for the domain model to ViewModel transport?

  • @Claudio

    Right now, working on getting it into a codeplex project, hopefully soon.

  • Pingback: Domain Entities Vs Presentation Model | C#Net()

  • Jimmy, as I understand you suggest to have a Model, EditModelDto and DisplayModelDto and you doing mapping using Automapper.
    For example, Person, DisplayPersonDto, EditPersonDto
    I see than you can “flatten” your model and convert Person -> DisplayPersonDto with Automapper without any side effect.
    What you are doing when converting from EditPerson to Person? Do you still use Automapper? In this case it may set something to 0 or empty when it is not allowed? How you doing it?