Geeks With Blogs
Łukasz Kuryło's blog

AutoMapper is very useful and flexible tool. Using it we can avoid writing stupic mapping code for each entity to it's DTO representation to send it e.g. throught web service.

If entity and dto object are mapping 1:1, there what we need to do is only write two lines of code:
 

Mapper.CreateMap<Article, ArticleDTO>(); //e.g. in Global.asax

and

var result=Mapper.Map<Article, ArticleDTO>(article);

It's not important, if Article class have ten or tousand fields. That's all. Think how horrible it is to map it manually.

A little bit more we have to do, if mapping is not 1:1.

Suppose we want to map class ArticleDTO:

public class ArticleDTO
{
//...
    public List<TagDTO> Tags { get; set; }
//...
}


to ArticlesViewModel class:

public class ArticlesViewModel
{
//...
    public IList<string> Tags { set; get; } //only tag names
//...
}


TagDTO contains tag name and its id.

In this situation we must "tell" to AutoMapper that, we want to use our custom ValueResolver. In the Global.asax we must change the declaration to:

Mapper.CreateMap<ArticleDTO, ArticlesViewModel>()
.ForMember(x => x.Tags, x => x.ResolveUsing<ExtractTagNamesValueResolver>().FromMember(y => y.Tags));


The second line is the same.

 

 

The ExtractTagNamesValueResolver is very simple:

public class ExtractTagNamesValueResolver : ValueResolver<object, IList<string>>
{
    protected override IList<string> ResolveCore(object source)
    {
        if (source is PersistentGenericBag<TagDTO>)
        {
            IList<string> result = new List<string>();
            PersistentGenericBag<TagDTO> elements = source as PersistentGenericBag<TagDTO>;

            foreach (TagDTO tag in elements)
            {
                result.Add(tag.Name);
            }

            return result;
        }

        return null;
    }
}


PersistentGenericBag<TagDTO> in this example is specific to NHibernate. In most cases I think, it will be ordinary IList<TagDTO>

 

Posted on Sunday, October 17, 2010 7:07 PM AutoMapper | Back to top


Comments on this post: Implementing custom ValueResolver for mapping with AutoMapper

Comments are closed.
Comments have been closed on this topic.
Copyright © Łukasz Kuryło | Powered by: GeeksWithBlogs.net