2012-04-11 118 views
0

我有以下類,我需要將Thread類中的帖子集合映射到ThreadView類中的帖子分頁集合,但我完全難以理解去解決它。AutoMapper - 使用構造函數映射子集合

// Database class 
public class Thread 
{ 
    public virtual int Id { get; set; } 
    public virtual string Title { get; set; } 
    public virtual IEnumerable<Post> Posts { get; set;} 
} 

// View class 
public class ThreadView 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    public PaginatedList<PostView> Posts { get; set; } 
} 

public class PaginatedList<T> : List<T> 
{ 
    public PaginatedList<IEnumerable<T> source, int page) 
    { 
     ... 
    } 
} 

我的映射是簡單的:

Mapper.CreateMap<Thread, ThreadView>(); 
Mapper.CreateMap<Post, PostView>(); 

而我的操作方法是這樣的:

public ViewResult ViewThread(int threadId, int page = 1) 
{ 
    var thread = _forumService.GetThread(threadId, page); 
    var viewModel = Mapper.Map<Thread, ThreadView>(thread); 

    return View(viewModel); 
} 

但是,這顯然是行不通的。誰能幫忙?

感謝

更新

我想我會滿足於做這樣的現在,即使它聞起來有點:

public ViewResult ViewThread(int id, int page = 1) 
{ 
    var thread = _forumService.GetThread(id, page); 
    var posts = Mapper.Map<IEnumerable<Post>, IEnumerable<PostView>>(thread.Posts); 

    var viewModel = new ThreadView { 
     Id = thread.Id, 
     Title = thread.Title, 
     Posts = new PaginatedList<PostView>(posts, page) 
    }; 

    return View(viewModel); 
} 

除非任何人知道如何這可以做到嗎?

回答

0

因爲看起來您無論如何都會返回所有Post項目,您可以修改該操作以從您的Thread對象而不是ThreadView創建PaginatedList。例如:

public ViewResult ViewThread(int threadId, int page = 1) 
{ 
    var thread = _forumService.GetThread(threadId, page); 
    thread.Posts = new PaginatedList(thread.Post, page); 
    var viewModel = Mapper.Map<Thread, ThreadView>(thread); 

    return View(viewModel); 
} 

有可能不是一個簡單的方法來使用AutoMapper。

編輯:哦,只是注意到頁面正在傳遞到您的服務。所以這個答案可能根本不是你想要的。讓我知道,如果是這樣的話,我會刪除它。

+0

感謝您的回覆。我認爲這可以工作,雖然PaginatedList是PostView的集合,它是從Post映射而來的。對不起,我沒有說清楚。我想我現在必須骯髒(見更新)。 – Tom 2012-04-11 15:24:09

+0

不用擔心 - 我認爲您的更新儘可能地接近您的需求。我會嘗試稍後與AutoMapper一起玩,如果我找到了某些東西,請編輯我的答案。 – Simon 2012-04-11 16:10:31