AutoMapper Map嵌套ICollection

时间:2015-11-06 18:25:29

标签: c# automapper

我想将一个调用映射到另一个调用,但是我一直都有异常/ 类型' AutoMapper.AutoMapperMappingException'发生在AutoMapper.dll中但未在用户代码中处理 /

以下是我的源类:

public class Snippet
{
    public Snippet()
    {
        this.Labels = new HashSet<Label>();
        this.Commennts = new HashSet<Comment>();
    }

    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    public string Description { get; set; }

    [Required]
    public string Code { get; set; }

    public int LanguageId { get; set; }

    public string UserId { get; set; }

    public DateTime CreatedOn { get; set; }

    public ICollection<Label> Labels { get; set; }

    public ICollection<Comment> Commennts { get; set; }

    public virtual Language Language { get; set; }

    public virtual ApplicationUser User { get; set; }
}

public class Label
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Snippet> Snippets { get; set; }
}

以下是我的目的地课程:

public class SnippetModels
{
    public class Output
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        public DateTime CreatedOn { get; set; }

        public string Code { get; set; }

        public string LanguageName { get; set; }

        public string UserUsername { get; set; }

        public IEnumerable<LabelModels.Output> Labels { get; set; }

        //TODO Comments Labels
    }
}

public class LabelModels
{
    public class Output
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }
}

public class HomeViewModel
{
    public IEnumerable<SnippetModels.Output> Snippets { get; set; }

    public IEnumerable<LabelModels.Output> Labels { get; set; }
}

最后,我把所有出现在我脑海中的东西都绑起来但没有成功:

Mapper.CreateMap<Snippy.Models.Label, LabelModels.Output>();
Mapper.CreateMap<IEnumerable<Snippy.Models.Label>, IEnumerable<LabelModels.Output>>();
Mapper.CreateMap<Snippy.Models.Snippet, SnippetModels.Output>()
    .ForMember(dest => dest.Labels, opt => opt.MapFrom(src => src.Labels));
Mapper.CreateMap<IEnumerable<Snippy.Models.Snippet>, IEnumerable<SnippetModels.Output>>();

var newestSnippetsDatabase = this.Data.Snippets
    .All()
    .OrderByDescending(s => s.CreatedOn)
    .Take(HomeVisibleItemsCount)
    .Select(s => s)
    .ToList();

var homeScreenView = new HomeViewModel
{
    Snippets = Mapper.Map<IEnumerable<SnippetModels.Output>>(newestSnippetsDatabase)
};

0 个答案:

没有答案