In Form-based application (WPF/MVVM/SQLServer), consider the form that handles the classical actions that you can perform on any entity.
- Create
- Read
- Update
- Delete
The problem, in general terms, is simple to tell.
which class of the viewmodel competes the call of any of the above actions?
What is clear:
* the ultimate actions compete to the model, that handles the business logic
What is unclear, i'll explain with this example.
Say that I have a model class that represent a Person
.
This class will have basic CRUD methods, say static NewInstance (C), static Load (R), Save (U), static static Delete(object key) (D).
Now the problem.
When I bring up a Person
instance, I most likely will do it through a PersonViewModel
, that will have expose a SaveCommand that in turn will call the save method of the underlying model.
Should this viewmodel have also the create command? This would be quite unnatural, because either:
the PersonViewModel is capable of undloading the underlying model and loading another one, thing that may be less than easy, depending on how much 'wiring' is going on between model and viewmodel
the command acts just as a relay for an external class that actually unloads the viewmodel and loads the new one. This is a bit contrived because in this case we have a code that unloads the object that contains it, and this requires additional assessments of correctness.
So all of these seems to be code smells that indicate that Create doesn't belong to PersonViewModel
.
Which class does it belongs to then?
I'm thinking of factory method in a 'viewmodel' variation. But solutions like that seems all to be over-engineered so I'm asking if there is a well-established pattern (possibly there are multiple ones) for this issue.