Bronzato
Bronzato

Reputation: 9332

Mapping with automapper

I have a domain model:

public class Project
{
    [Key]
    public int ProjectID { get; set; }
    public string Title { get; set; }
    public string Slug { get; set; }
    public string Content { get; set; }
    public string Category { get; set; }
    public string Client { get; set; }
    public int Year { get; set; }
}

I have a view model (which is a portion of the above model):

public class ListProjectsViewModel
{
    public IEnumerable<ProjectStuff> SomeProjects { get; set; }

    public class ProjectStuff
    {
        public int ProjectID { get; set; }
        public string Title { get; set; }
        public string Slug { get; set; }
        public string Content { get; set; }
    }

    // Some other stuff will come here
}

I have an action controller:

    public ActionResult List()
    {
        // Get a list of projects of type IEnumerable<Project>
        var model = m_ProjectBusiness.GetProjects();

        // Prepare a view model from the above domain entity
        var viewModel = Mapper.Map..........
        return View(viewModel);
    }

How can I code the mapping '........' with automapper ?

Thanks.

Upvotes: 1

Views: 844

Answers (1)

Dismissile
Dismissile

Reputation: 33071

There are two steps.

1) Define a mapping with AutoMapper (this is usually done in some sort of bootstrapper called by Global.asax, etc.)

// since all of your properties in Project match the names of the properties
// in ProjectStuff you don't have to do anything else here
Mapper.CreateMap<Project, ListProjectsViewModel.ProjectStuff>();

2) Map the object in your controller:

// Get a list of projects of type IEnumerable<Project>
var projects = m_ProjectBusiness.GetProjects();

// Prepare a view model from the above domain entity
var viewModel = new ListProjectsViewModel
{
    SomeProjects = Mapper.Map<IEnumerable<Project>, IEnumerable<ListProjectsViewModel.ProjectStuff>>(projects)
};

return View(viewModel);

The thing to note here is that you are defining a mapping between Project and ProjectStuff. What you are trying to map is a list of Projects (IEnumerable) to a list of ProjectStuff (IEnumerable). AutoMapper can do this automatically by putting that in the generic arguments as I did above. Your View Model that your view is using is wrapping your list of ProjectStuff, so I just create a new ListProjectsViewModel and do the mapping inside of that.

Upvotes: 3

Related Questions