2

I currently have a repository based on Entity Framework v4 entities (CRUD and GET operations implemented). I'm in the process of creating the corresponding View Models for these entities. Where should I put the conversion/mapping between them? In the controller or modify the repository to perform the mapping in its methods and return back (or accept) the View Model typed objects?

Should I do this

    public ActionResult Index()
    {
        var person = new PersonRepository().Get();

        var personViewModel = new PersonViewModel();
        personViewModel.InjectFrom(person)
            .InjectFrom<CountryToLookup>(person);

        return View(personViewModel);
    }

or this

     public ActionResult Index()
        {
            var personViewModel = new PersonRepository().Get(); // returns object of type PersonViewModel

// and move this to repository
//            var personViewModel = new PersonViewModel();
//            personViewModel.InjectFrom(person)
//               .InjectFrom<CountryToLookup>(person);

            return View(personViewModel);
        }
mare
  • 13,033
  • 24
  • 102
  • 191
  • 1
    since you're using valueinjecter I strongly recommend you to look at the source code of the live demo from here http://awesome.codeplex.com/, look at the Cruder (Controller) and implementations of IBuilder – Omu Jan 19 '11 at 18:15

2 Answers2

3

I would extract it out into a private method on the controller or put it into a service class if it's going to be reused in other places.

I don't think it's a good idea putting it on the repository unless it's not generic. Which it should be because in my opinion generic repositories rock!

4imble
  • 13,979
  • 15
  • 70
  • 125
1

I would never put transformation code into your repository.

  • Repositories abstract data access from other concerns. Views abstract
  • UI formatting from other concerns.

Mixing the two is just throwing all of your careful decoupling away.

The book definition of MVC strongly implies transformation should be done inside the controller:

"The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input."

John Farrell
  • 24,673
  • 10
  • 77
  • 110