2011-12-29 33 views
0

我有以下实体模型:需要从两个对象映射到一个单一的一个

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; } 
    // more attributes here... 
} 

我想准备(具体为我的视图)视图模型。这里是视图模型:

public class ProjectListViewModel 
{ 
    public IEnumerable<ProjectInfos> ProjectList { get; set; } 
    public PagingInfo Paging { get; set; } 

    public class ProjectInfos 
    { 
     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 PagingInfo 
    { 
     public int TotalItems { get; set; } 
     public int ItemsPerPage { get; set; } 
     public int CurrentPage { get; set; } 
     public int TotalPages { get; set; } 
    } 
} 

在我的控制,我想用2个不同的对象填充它编写视图模型:

  1. 的项目清单
  2. 寻呼信息

这里是我的控制器:

public ViewResult List(string category, int page = 1) 
{ 
    IEnumerable<Project> projectList = m_Business.GetProjects(category, page, 10); 
    PagingInfo pagingInfo = m_Business.GetPagingInfo(category, page, 10); 

    // Here I need to map !! 
    ProjectListViewModel viewModel = ..... 

    return View(viewModel); 
} 

那么我该如何在我的控制器中进行操作?我知道我们可以使用automapper从一个对象映射到另一个对象,但在这里我需要从两个对象映射到一个对象。

谢谢。

+0

可能重复[?如何处理与多个集合根视图模型(http://stackoverflow.com/questions/2020499/how-to-处理视图模型与多个聚合根) – 2011-12-29 14:25:18

回答

6

您可以扩展AutoMapper以映射多个对象。

Here is a blog它提供了一些样品应付。

然后你可以使用这样的代码:

var personViewModel = EntityMapper.Map<PersonViewModel>(person, address, comment); 
+0

+1,非常漂亮的扩展。 – 2011-12-29 13:14:00

+0

@Darin:谢谢,但有可能在视图模型中嵌入类,就像我的问题一样?我下载了博客中提供的示例,并尝试使用一个嵌套类来尝试Map,但失败。 – Bronzato 2011-12-29 13:38:41

+0

@Darin:我的意思是,让我们来看看url中提供的博客,在这个例子中,他的视图模型类包含一些属性(全部在同一级别),但没有嵌套类。我想我的视图模型包含对象的解决方案。谢谢。 – Bronzato 2011-12-29 13:50:47

相关问题