Automapper - 如何映射到IEnumerable

时间:2014-12-30 09:30:11

标签: c# asp.net-mvc automapper

我正在制作论坛系统,我有SubCategoryThreadsViewModel,其中我试图为每个帖子映射LastComment和最后一篇帖子的日期。这是我的代码:

public class SubCategoryThreadsViewModel : IHaveCustomMappings
{
    public string Title { get; set; }

    public string Description { get; set; }

    public IEnumerable<Thread> Threads { get; set; }

    public ThreadInfoSubCategoryViewModel ThreadInfoSubCategoryViewModel { get; set; }

    public void CreateMappings(IConfiguration configuration)
    {
        configuration.CreateMap<Thread, SubCategoryThreadsViewModel>()
            .ForMember(m => m.Title, opt => opt.MapFrom(t => t.SubCategory.Title))
            .ForMember(m => m.Description, opt => opt.MapFrom(t => t.SubCategory.Description))
            .ForMember(m => m.Threads, opt => opt.MapFrom(t => t.SubCategory.Threads))
            .ForMember(m => m.ThreadInfoSubCategoryViewModel, opt => opt.MapFrom(t => new ThreadInfoSubCategoryViewModel()
            {
                  LastCommentBy = t.Posts.Select(a => a.Author.UserName),
                  DateOfLastPost = t.Posts.Select(a => a.CreatedOn.ToString()),
            }))
            .ReverseMap();
    }

代码

.ForMember(m => m.ThreadInfoSubCategoryViewModel, opt => opt.MapFrom(t => new ThreadInfoSubCategoryViewModel()
        {
              LastCommentBy = t.Posts.Select(a => a.Author.UserName),
              DateOfLastPost = t.Posts.Select(a => a.CreatedOn.ToString()),
        }))

正在工作,但只有当属性ThreadInfoSubCategoryViewModel不是上面代码中的Ienumerable时,内部是两个IEnumerable字符串。

public class ThreadInfoSubCategoryViewModel
    {
        public IEnumerable<string> LastCommentBy { get; set; }

        public IEnumerable<string> DateOfLastPost { get; set; }
    }

这样可行,但是我希望ThreadInfoSubCategoryViewModel是Ienumerable,并且在类属性中是字符串以便于foreach。

我试图让它成为IEnumerable,但是使用当前的自动化代码它并不起作用。

1 个答案:

答案 0 :(得分:0)

您需要手动将成员映射到IEnumerable<ThreadInfoSubCategoryViewModel>而不是单个对象。

我假设Post中的每个t.Posts代表一个ThreadInfoSubCategoryViewModel,因此一个简单的Select()应该这样做:

public IEnumerable<ThreadInfoSubCategoryViewModel> ThreadInfoSubCategoryViewModel { get; set; }

...

.ForMember(m => m.ThreadInfoSubCategoryViewModel, opt => opt.MapFrom(t =>
    t.Posts.Select(p => new ThreadInfoSubCategoryViewModel()
    {
        LastCommentBy = p.Author.UserName,
        DateOfLastPost = p.CreatedOn.ToString()
    })
))