使用automapper进行映射

时间:2011-12-29 20:51:20

标签: asp.net-mvc automapper

我有一个域名模型:

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; }
}

我有一个视图模型(它是上述模型的一部分):

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
}

我有一个动作控制器:

    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);
    }

如何使用automapper编写映射'........'?

感谢。

1 个答案:

答案 0 :(得分:3)

有两个步骤。

1)使用AutoMapper定义映射(这通常在Global.asax等调用的某种引导程序中完成)

// 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)在控制器中映射对象:

// 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);

这里需要注意的是,您正在定义Project和ProjectStuff之间的映射。您要映射的是项目列表(IEnumerable)到ProjectStuff(IEnumerable)列表。 AutoMapper可以通过将其放在通用参数中自动执行此操作,如上所述。您的视图正在使用的View模型包含了ProjectStuff列表,因此我只需创建一个新的ListProjectsViewModel并在其中进行映射。