【问题标题】:AutoMapper - mapping a child collection with a constructorAutoMapper - 使用构造函数映射子集合
【发布时间】:2018-04-18 16:42:57
【问题描述】:

我有以下类,我需要将 Thread 类中的帖子集合映射到 ThreadView 类中的分页帖子集合,但我完全不知道如何去做。

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

除非其他人知道如何做到这一点?

【问题讨论】:

    标签: c# collections pagination automapper


    【解决方案1】:

    看起来您无论如何都返回了所有 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 可能不是一个简单的方法。

    编辑:哦,刚刚注意到页面正在传递到您的服务中。所以这个答案可能根本不是你想要的。让我知道,如果是这样,我会删除它。

    【讨论】:

    • 感谢您的回复。我认为这可行,尽管 PaginatedList 是 PostView 的集合,它是从 Post 映射的。对不起,我没有说清楚。我想我现在不得不玩肮脏(见更新)。
    • 不用担心 - 我认为您的更新已尽可能接近。稍后我会尝试使用 AutoMapper 进行游戏,如果我发现了什么,我会编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2015-07-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多