简体   繁体   English

AutoMapper-使用构造函数映射子集合

[英]AutoMapper - mapping a child collection with a constructor

I have the following classes, and I need to map the collection of posts in the Thread class to a paginated collection of posts in the ThreadView class, but I'm completely stumped on how to go about it. 我有以下类,我需要将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)
    {
        ...
    }
}

My mappings are simply: 我的映射很简单:

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

And my action method looks like this: 我的操作方法如下所示:

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

    return View(viewModel);
} 

But this obviously doesn't work. 但这显然不起作用。 Can anyone help? 有人可以帮忙吗?

Thanks 谢谢

Update 更新资料

I think I'm gonna settle for doing it like this for now, even though it smells a bit: 我想我现在会喜欢这样做,即使它闻起来有点:

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

Unless anyone else knows how this can be done? 除非其他人不知道该怎么做?

As it appears you are returning all the Post items anyway, you could modify the action to created the PaginatedList from your Thread object instead of ThreadView. 看起来您无论如何都返回所有Post项目,您可以修改操作以从Thread对象而不是ThreadView创建PaginatedList。 Something like: 就像是:

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

There's probably not an easy way to do just using AutoMapper. 仅使用AutoMapper可能不是一个简单的方法。

EDIT: Oh, just noticed the page is being passed into your service. 编辑:哦,刚注意到页面正在传递到您的服务中。 So this answer probably isn't at all what you want. 因此,这个答案可能根本不是您想要的。 Let me know and I'll delete it if that's the case. 让我知道,如果是这种情况,我将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM