Using Automapper ValueResolver for complex, reusable mapping

Tuesday, October 23, 2012
Automapper is a great tool to help automate the tedious task of mapping Domain Model to View Model and back.  However, sometimes, mappings are not as straightforward as a simple one to one, left to right mapping.  The example below is a real-world implementation of ValueResolver for mapping date of birth to age:

using System;
using AutoMapper;

namespace SomeCompany.SomeProject.Web.Models.ValueResolvers
{
    public class AgeValueResolver : ValueResolver<DateTime?, int>
    {
        protected override int ResolveCore(DateTime? dateOfBirth)
        {
            if (dateOfBirth.HasValue)
            {
                var age = DateTime.Today.Year - dateOfBirth.Value.Year;

                if (dateOfBirth.Value > DateTime.Today.AddYears(-age))
                {
                    age--;
                }

                return age;
            }

            return 0;
        }
    }
}

To use this within your mapping, you could do something like:

CreateMap<IPerson, PersonViewModel>()
  .ForMember(dest => dest.Age, opt => opt.ResolveUsing<AgeValueResolver>().FromMember(src => src.DOB));

6 comments:

Robert F. Crocker said...

Its very nice to see your contribution in this post. You have shown your talent and experience in your post. Thanks for sharing this post with all. psd to html

for IT the said...

Automapper is a great tool to help automate the tedious task Dot Net Training in Chennai C# real-world implementation of ValueResolver for mapping date C-Sharp Courses C# Training

Arjun Rishi said...

You shared useful post. Happy to visit your blog. Thanks for sharing.

seo training in chennai

Anu Sri said...

Excellent post! Thanks for sharing such a useful post.

web design course in chennai

Logavani G said...

hi welcome to this blog.really you have post an informative blog.it will be really helpful to many peoples.
codedUI training

Mohana M said...

Thank you admin for your valuable article. I really impressed with your blog. SAS Training in Chennai | Devops Online Training | SQL Server DBA Online Training

Post a Comment