0

want to get rid of ViewBag in my views so i've made a little research about viewmodels. i like the idea of using it for presentation, no questions here. but i don't realise what is the best way to use viewmodels for update.

first of all, why shouldn't i use my EF entities with [MetadataType(typeof(User_Validation))]?

public ActionResult Edit(User user) 
{
    ...
}

where User is EntityObject.

then, if i however use viewmodels for it there is another question: here people believe that nested viewmodels should be used, but here is another opinion ("They are not wrappers around domain models", he says). Who is right?

also, what is the best way to update an object in action after POST (without using tryupdatemodel, because here and not only, people are against this approach). i've tried to use ApplyCurrentValues but if there is some complicated logic of update with many-to-many relations, for example, i get some huge EF errors. that's why i need to manually set fields of my EntityObject that i get from DB with values that come to action. Smth like this:

public ActionResult Edit(User user) 
{
    if (ModelState.IsValid)
    {
        var userToUpdate = usersRepository.Get(user.UserId);
        userToUpdate.Field1 = user.Field1;
        ...
        // save
    }
    ...
}

where User is EntityObject with validation class.

so, if i use flat viewmodels to get values from form and AutoMapper to set values to my entityobject will it be the most right way to deal with updates or it can be automatized even more?

Community
  • 1
  • 1
donRumatta
  • 836
  • 2
  • 9
  • 22

1 Answers1

1

You answered yourself in the last paragraph. I am using the exactly same approach in my MVC3 EF Code First project.

Here is the practice I follow:

  1. All entity classes are clubbed under one folder "Entity". You can also opt for a separate library project.
  2. Every entity has a corresponding ViewModel class with a postfix of Model (e.g. for Profile entity there is ProfileModel class).
  3. For nested entities there are corresponding nested ViewModel classes.
  4. AutoMapper is used for Model to Entity and vice versa conversions. Here automapper takes care of the nested entities. In case of complex updates, rather than relying on AutoMapper, I take the matter in my own hands in controller.
  5. Works flawlessly with healthy separation between my domain objects and view models.
Prafulla
  • 1,929
  • 1
  • 17
  • 21
  • and what about validation. if i use ef objects i add attributes in one place and the validation happens every time in different places. but if i use different viewmodels will i have to duplicate validation logic? – donRumatta Dec 13 '11 at 11:29
  • I duplicate the annotations on ViewModel classes. That way client/server/programmatic manipulations all get validated. – Prafulla Dec 13 '11 at 11:33