tags:

views:

130

answers:

2

As a new fan of AutoMapper, how would I use it to do the following:

Given the following classes, I want to create FlattenedGroup from Group where the list of item string maps to the title property of Item.

public class Group
{
    public string Category { get; set; }
    public IEnumerable<Item> Items { get; set; }
}

public class Item
{
    public int ID { get; set; }
    public string Title { get; set; }
}


public class FlattenedGroup
{
    public string Category { get; set; }
    public IEnumerable<string> Items { get; set; }
}

Thanks

Joseph

+1  A: 

Give this a try, you can probably use Linq and a lambda expression to map the list of strings in FlattenedGroup with the titles in Group.

Mapper.CreateMap<Group, FlattenedGroup>()
                .ForMember(f => f.Category, opt => opt.MapFrom(g => g.Category))
                .ForMember(f => f.Items, opt => opt.MapFrom(g => g.Items.Select(d => d.Title).ToList()));

Make sure you add System.Linq to your using statements

Scozzard
+3  A: 

The other thing you can do is create a converter from Item -> string:

Mapper.CreateMap<Item, string>().ConvertUsing(item => item.Title);

Now you don't need to do anything special in your Group -> FlattenedGroup map:

Mapper.CreateMap<Group, FlattenedGroup>();

That's all you'd need there.

Jimmy Bogard
Nice! Cheers for Automapper too its a cool tool
Scozzard

related questions