使用automapper将模型集合映射到viewmodel

时间:2012-06-27 15:04:19

标签: automapper

我希望使用automapper将模型集合映射到viewmodel 这是我的代码

public class LanguageViewModel
    {
        public string Name { get; set; }
        public IList<Word> Categories { set; get; }
        public IList<string> PictureURL { set; get; }
    }

这是我的模特

public class Word : BaseFieldsTables
{
    public string Text { get; set; }
    public virtual Category Category { get; set; }
    public int CategoryID { get; set; }
    public virtual Language Language { get; set; }
    public int LanguageID { get; set; }

    public virtual ICollection<Picture> Pictures { get; set; }

    [InverseProperty("MainWord")]
    public virtual ICollection<RelationshipBetweenWords> MainWords { get; set; }

    [InverseProperty("RelatedWord")]
    public virtual ICollection<RelationshipBetweenWords> RelatedWords { get; set; }
}

1 个答案:

答案 0 :(得分:0)

在他的例子中,您从顶级域模型开始,并将其映射到名为Nested mappings的内部集合。

mapper.CreateMap<Word , LanguageViewModel>()                
    .ForMember(dest => dest.Name, src => src.MapFrom(s => s.Text));

对于Word域模型中的内部集合,您需要为“类别”和“图片”定义单独的映射。

mapper.CreateMap<Picture, PictureModel>()                
   .ForMember(dest => dest.PictureURL , src => src.MapFrom(x => x.Picture.Urltext));

mapper.CreateMap<Category, CategoryModel>()                
   .ForMember(dest => dest.CategoryId, src => src.MapFrom(x => x.Category.CategoryInt));

并且对于所有剩余的内部集合,您需要定义映射以使其工作