MVVM:How am I supposed to convert a ViewModel into a Model?
everyone speaks about wrapping a model by a viewmodel. fine so far.
But when I want persist my Model, how do I convert开发者_如何学C a ViewModel into a Model ?
Reading all properties from the ViewModel into a new Model object seems very cumbersome.
Any better method?
I'm currently converting an old winforms app into a wpf mvvm application, and I'm just providing a property on my viewmodel that points to the actual instance of the model.
From my point of view, it doesn't make sense to create a replica of the model in the viewmodel, and I don't think that the MVVM community is saying that anyway.
It particularly won't make sense when you start using entity framework or some other database orm, because entity framework has properties that support databinding out of the box. Plus, when you start making changes to the database, you have to update the model, and the viewmodel.
Edit: You're right in that ef doesn't support INotifyCollectionChanged, but as far as I know, it does support INotifyPropertyChanged, and from the looks of it, Microsoft is thinking of implementing INotifyCollectionChanged in a future release.
I don't think that there is a right or wrong way for MVVM - I think that every different 'authority' on the web has their own interpretation of how it should work.
The idea is that the ViewModel is made for the user interface. In other words, one WPF form has one ViewModel, while the ViewModel may actually use multiple models (customers, orders, etc.). If your form is only dealing with one model, then it is going to be close to a 1-to-1 mapping.
Only wrap a model in a viewmodel when needed, otherwise the view will directly bind to the properties of your model. An example: Model 1: list of employees (An employee has a name and department) Model 2: list of departments. View: Show list of employees and departments. When a user selects a department, the employee list gets filtered. ViewModel: Provide a current selected department property and a filtered employee list.
View would databind the department list directly against the model 1 but the current selected department and filtered employee list against the viewmodel. Viewmodel will filter employee list depending on selected department.
If you don't want to replicate the properties, I'd suggest to use regular models and Django>=1.4 proxy models:
- use regular models for persisting your data and
- use proxy models when you would use view models.
Proxy models are easily defined by inheriting the original model and adding proxy = True
to your model Meta
, e.g.
class MyProxyModel(MyModel):
class Meta(MyModel.Meta):
proxy = True
# Add here the desired view model methods...
Note that proxy models don't need to be defined in the models.py
-- I often use proxy models on the admin site and define them in the admin.py
.
Hope this helps or that other late-comers like me can use this.
精彩评论