There are a lot of articles about using MVVM patterm for ASP .NET MVC. For example, it is http://blogs.microsoft.co.il/blogs/helpercoil/archive/2010/08/28/asp-net-mvc-and-the-mvvm-pattern.aspx.
There is only one question for me. We have a lot of ViewModels for one Model. How can I fill Model properties automatic by using viewModel object? How to make automatic property mapping?
I use Entity Framework.
For example, I have model Test with the following properties:
- id
- name
- title
- idUser
- idCompany
I made ViewModel for my task. This ViewModel (TestUserViewModel) uses for simple user with the following properies:
– id
– name
– title
For example, user edit an existing test. As the result, we have an object with type TestUserViewModel. I want:
- synchronize Model object and ViewModel.
- save the default valies for idCompany, idUser – for properties, which were excluded from current ViewModel.
-
use some automatic stuff – it may be something like ApplyCurrentValues. I really don’t want to write a lot of following code:
modelObj.name=viewModelObj.name; modelObj.title=viewModelObj.title;
Using System.Reflexion for this looks like bad, too.
So, how to do it?
If you don’t want to write a lot of mapping code from one object to another you might want to look into mapping tools like AutoMapper http://automapper.org/
Having said that, as @Darin Dimitrov pointed out, you should review your architecture too. If you are doing ASP.NET MVC you should become more familiar with MVC rather than MVVM. As you read more about how to use MVC you are going to start seeing the use of “viewModels”. Keep in mind that these “viewModels” in MVC have nothing to do with “VM” in “MVVM”.