1
votes

in my ASP MVC 2 application I follow the strongly typed view pattern with specific viewmodels.

Im my application viewmodels are responsible for converting between models and viewmodels.
My viewmodels I have a static ToViewModel(...) function which creates a new viewmodel for the corresponding model. So far I'm fine with that.

When want I edit a model, I send the created viewmodel over the wire and apply the changes to back to the model. For this purpose I use a static ToModel(...) method (also declared in the view model). Here the stubs for clarification:

public class UserViewModel
{
    ...
    public static void ToViewModel(User user, UserViewModel userViewModel)
    {
        ...
    }

    public static void toModel(User user, UserViewModel userViewModel)
    {
        ???
    }
}

So, now my "Problem": Some models are complex (more than just strings, ints,...). So persistence logic has to be put somewhere.
(With persistence logic I mean the decisions wheater to create a new DB entry or not,... not just rough CRUD - I use repositories for that)

I don't think it's a good idea to put it in my repositories, as repositories (in my understanding) should not be concerned with something that comes from the view.
I thought about putting it in the ToModel(...) method but I'm not sure if thats the right approach.

Can you give me a hint?

Lg
warappa

2
Updated title to direct focus on where to put persistence logicDavid Rettenbacher

2 Answers

0
votes

Warappa - we use both a repository pattern and viewmodels as well.

However, we have two additonal layers:

  • service
  • task

The service layer deals with stuff like persisting relational data (complex object models) etc. The task layer deals with fancy linq correlations of the data and any extra manipulation that's required in order to present the correct data to the viewmodel.

Outwith the scope of this, we also have a 'filters' class per entity. This allows us to target extension methods per class where required.

simples... :)

0
votes

In our MVC projects we have a seperate location for Converters.

We have two types of converter, an IConverter and an ITwoWayConverter (a bit more too it than that but I'm keeping it simple).

The ITwoWayConverter contains two primary methods ConvertTo and ConvertFrom which contain the logic for converting a model to a view model and visa versa.

This way you can create specific converts for switching between types such as:

public class ProductToProductViewModelConverter : ITwoWayConverter<Product,ProductViewModel>

We then inject the relevant converters into our controller as needed.

This means that your conversion from one type to another is not limited by a single converter (stored inside the model or wherever).