Where to convert business model to view model?

Viewed 9304

In my ASP.NET MVC application, I am using unit of work and repository patterns for data access.

Using the unit of work class and the repository defined inside it I am fetching the related set of entities in my controller. With my beginner knowledge, I can think of two ways to fetch the business model and convert it to view model.

  • Repository returns the business model to controller, this model than mapped to view model, or
  • Repository itself converts business model to view model and then it is returned to controller.

Currently I am using first approach, but my controller code started to look ugly and long for view models with lots of properties.

On the other hand, I am thinking, since my repository is called UserRepository (for example), it should be returning the business model directly, instead of some model that is useful only for single view.

Which one of these do you think is better practice for large projects ? Is there an alternative way ?

3 Answers

As mentioned in other answers, AutoMapper is a good solution.

However you can also write extension methods to convert your Entity to ViewModel and vice versa. Maybe this is better for smaller projects with fewer Entity and Model classes.

Example:

public static class Extension
{
    public static MyViewModel ToModel(this MyEntity x)
    {
        return new MyViewModel
        {
            Id = x.Id,
            Name = x.FirstName + " " + x.LastName,
            UserId = x.User?.Id
        };
    }
}

And to use:

// NOTE: "MyEntityTable" is of type "MyEntity"

List<MyViewModel> toReturn = _db.MyEntityTable
                  .Include(x => x.User) // Include other tables to join.
                  .Select(x => x.ToModel())
                  .ToList();
Related