tags:

views:

48

answers:

3

How do you handle situations where you have Model classes based on SQL tables, for instance when using Entity Framework to generate the Entities and data access for you but you would still like one or two properties to be different and/or excluded.

I have no problem having separate View Model classes and Model classes but there's more and more occasions where differences are only minor. So I end up copying Model class properties to the View model class and change/remove the property I want.

So, in a sense I would like to follow the pattern of separate Model and View Model classes but it's often time consuming just to achieve the removal of dependency between Views and Models - I could just use the Model class in the View.

+1  A: 

I never use domain models in POST actions (to accumulate user input) - well, except when binding by entity ID to db. But I do sometimes pass them to views. It's actually bad - you can't see what view really needs, and you often start to create business logic queries inside view - but when this gets even a bit bad (e.g. view needs to convert domain model somehow to query/filter data), it's rather easy to add a view model and change it to a proper implementation. In some sense this is KISS/YAGNI at best - if it works and there're no drawbacks, why not? Change it to something more complex only situation starts to require it.

queen3
A: 

You could simply make your ViewModel a subclass of your Model. As needed, you could refactor your ViewModels and even remove its inheritance from your Model.

You are right to anticipate the potential downsides of passing domain models to your view, but there's no rule against keeping things simple if it works for you.

Larsenal
Subclassing actually makes sense. I can have separate files/classes and still use the implementation that already exists in EF. When I need it in future, I can remove the inheritance and implement it another way.
mare
A: 

You also have the option of creating a viewmodel as a simple property-wise copy of your model and then relying on something like Automapper to handle the mapping. Generally, I prefer to keep my domain models in a separate assembly - inheritance would work, I haven't tried it. Pulling an inheritance hierarchy across this assembly boundary seems like a bit much. If your viewmodels are identical to your domain models, or similar enough that you can get away with using your domain models in your UI tier, then automapper and even deriving or creating a copy of your model might be overkill.

RG