views:

65

answers:

1

Title pretty much explains it all, its the last thing I'm trying to work into our project. We are structured with a Service Library which contains a function like so.

        /// <summary>
        /// Returns a single category based on the specified ID.
        /// </summary>
        public Category GetCategory(int CategoryID)
        {
            var RetVal = _session.Single<Category>(x => x.ID == CategoryID);
            return RetVal;
        }

Now Category is a Entity (We are using Entity Framework) we need to convert that to a CategoryViewModel.

Now, how would people structure this? Would you make sure the service function returned a CategoryViewModel? Have the controller pull the data from the service then call another function to covnert to a view model?

+2  A: 

Here's an excerpt from a blog post I wrote:

[AutoMap(typeof(IEnumerable<User>), typeof(IEnumerable<UserViewModel>))]
public ActionResult Index()
{
    // return all users
    IEnumerable<User> users = Repository.GetUsers();
    return View(users);
}

In this case the corresponding view is strongly typed to IEnumerable<UserViewModel>. It uses AutoMapper to define conversion rules between entities and view models. As for the [AutoMap] attribute, it's a custom action filter which inspects the model passed to the view and applies the proper conversion so that the view has only the view model.

Darin Dimitrov
@Darin Dimitrov Very elegant solution +1 for that! I'm wary of AutoMapper because of the reflection useage. If the site was recieving 3 request per second is AutoMapper somthing to be concerned about?
Pino
Darin Dimitrov
@Darin Dimitrov - Thanks :) - In your example where do "IModelMapperController" and "controller.ModelMapper" come from?
Pino
`IModelMapperController` is an interface implemented by my BaseController (not shown in the blog article, I invite you to look at the source code: http://github.com/darind/samplemvc)
Darin Dimitrov