0

I'm trying to use Automapper v3 to map from my Post struct to my Postmodel class. I need to map Term Name to my Categories array but only if the Type equals "Category".

Here's my code

    public class NewsModel
    {

        public NewsModel(int id)
        {

             Mapper.Initialize(cfg =>
            {

                cfg.CreateMap<Post, PostModel>();

            });

            Posts = new List<PostModel> {Mapper.Map<PostModel>(_newsGetter.GetItem(id))};
        }

        public List<PostModel> Posts { get; set; }

    }

Map to this class

    public class PostModel
    {

        public String[] Categories { get; set; }

    }

Map from this Struct

    public struct Post
    {

        public Term[] Categories { get; set; }

    }

    public Struct Term
    {
         public string Name{ get; set; }
         public string Type{ get; set; }

    }

Any help is greatly appreciated.

heymega
  • 9,215
  • 8
  • 42
  • 61
  • What did you try so far? What didn't work? – samy Apr 09 '14 at 13:06
  • I've tried using the ForMember method which I cant get to work. Every example I've seen uses a lamba expression but that's not in any of the overrides as far as I can tell :/ – heymega Apr 09 '14 at 13:27

1 Answers1

0

The simplest solution would be to map the filtered categories from the Post to the PostModel.

cfg.CreateMap<Post, PostModel>()
.ForMember(pm => pm.Categories
           , o => o.MapFrom(p => p.Categories.Where(t => t.Name != "Category")));

Then simply convert the Term to a string using ConvertUsing

cfg.CreateMap<Term, string>().ConvertUsing(t => t.Name);
samy
  • 14,832
  • 2
  • 54
  • 82