AutoMapper: the Object-Object Mapper

In Domain-Driven Design, creating a rich domain model in code is essential for capturing the richness and complexity of the real-world domain.  These domain models, designed as POCOs, are not very portable, nor should they be.  Domain models live inside the domain layer, not to be exposed to the outside world.  Very often, we don’t want to expose these models to other layers of our application.  To mitigate this issue, we often create various sorts of other models, like DTOs, ViewModels, messages, and so on.  Two things were in common with these objects:

  • Mapping code is tedious to write
  • Mapping code is tedious to test

In fact, some of the most boring code in the world to write is mapping between two objects, as it often looked something like this:

public class OrderToOrderViewModelMapper
    public OrderViewModel Map(Order order)
        return new OrderViewModel
                CustomerFullName = order.Customer.GetFullName(),
                Total = order.GetTotal(),
                LineItems = order.GetLineItems()
                    .Select(x => new OrderLineItemViewModel
                            Price = x.Price,
                            Quantity = x.Quantity,
                            Total = x.GetTotal(),
                            ProductName = x.Product.Name

That’s quite a bit of code to write, test and maintain, especially when all I’m trying to do here is carve a slice out of my rich domain model for consumption for something else, whether it’s my MVC view, JSON, a reporting application, and so on.  I hated writing this code over and over again, so instead our team brainstormed and decided to create an auto-mapper.

Enter the AutoMapper

If you look closely at the mapping logic above, the design of my destination type looks awfully similar to our domain model, just flattened out.  Let’s do that mapping code with AutoMapper:

public static void Configure()
    Mapper.CreateMap<Order, OrderViewModel>();
    Mapper.CreateMap<OrderLineItem, OrderLineItemViewModel>();

Whew, that was tough!  I create two maps, for each source/destination pair (remember, I had to map the OrderLineItem to the child line items as well).  Why don’t we actually use the Mapper to execute a map:

var viewModel = Mapper.Map<Order, OrderViewModel>(order);

Sweet fancy Moses, I’m out of breath.  But I lost my tests around the mapping code.  How do I make sure my configuration is valid?  From a feature I lifted from StructureMap:


This will throw an AutoMapperConfigurationException (with details on the offending source type, destination type, and offending property(s).  AutoMapper enforces that for each type map (source/destination pair), all of the properties on the destination type are matched up with something on the source type.  Since AutoMapper matches type members up by name, you’re really looking at misspelled/missing members.

You do lose a little refactoring friendliness, but you’ll get the one-line descriptive test to let you know where you went awry.

AutoMapper conventions

Since AutoMapper flattens, it will look for:

  • Matching property names
  • Nested property names (Product.Name maps to ProductName, by assuming a PascalCase naming convention)
  • Methods starting with the word “Get”, so GetTotal() maps to Total
  • Any existing type map already configured

Basically, if you removed all the “dots” and “Gets”, AutoMapper will match property names.  Right now, AutoMapper does not fail on mismatched types, but for some other reasons.

AutoMapper feature rundown

AutoMapper supports:

  • Mapping of simple types
  • Mapping to arrays from any IEnumerable source
  • Custom member resolution, for that 1% case you have to do some extra mapping work
  • Polymorphic array mapping
  • Custom formatting for mapping from any type to a string
  • Global formatters
  • Null substitutes for formatting (i.e. a missing Product formats to “n/a”)
  • Profiles, for separating different sets of configurations (JSON vs. ViewModel vs. EditModel etc)

Other features include:

  • Convention of no null destination objects, ever.
  • No null destination array properties, ever.
  • A fluent configuration, with both a method chaining syntax (through Mapper) and object scoping (through a Profile)

What’s missing:

  • Auto-registration (mainly because you then can’t test it easily)
  • Support for conversion operators, as these are compile-time, not run-time in C#.  I can do it, but only by reflection and looking for crazy method names
  • Documentation

There are specs, mostly organized by feature area in the source code.  AutoMapper was built completely with TDD, so there aren’t any features that don’t have a test (and aren’t used in a production system).  You can find the latest release at the CodePlex site:

The source is hosted on my favorite free SVN host, Google Code:


About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in AutoMapper. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Jimmy, I love this tool. Is there a way to use automapper to update an entity with a view model, rather than creating a new entity?

  • Thanks Jimmy, looks brilliant. I think I’ll be test driving this at the same time as Fluent NHibernate for a “walk in the park” db->model->viewmodel mapping experience :)

  • Damn, I’ve been wanting to do this kind of project for so long. Oh well – at least now I can be lazy instead.

    Gonna have a look at it :-)

  • Looking good, gonna have a look at it!

  • Also wrote something similar a while back – details here:

    I like what you’ve done with the Method to Property mapping, and the automatic handling of nested types; might pick up those ideas in mine at some point.

  • @Liam

    That’s something we’ve looked at for a while (two-way binding), but in the end, we found that there was just too much business validation in an Update.

    Instead, we formed other patterns around updating a model from a message/form. See Code Camp Server source for more details.

  • Jeff Gonzalez

    Man – love it!

    This is yucky, but there seems to be no support for this:

    Mapper.CreateMap , List>();

    var results = Mapper.Map , List>(dogs);

    Probably a good thing – it’ll force me to not do silly things like that, but would be nice on occasion.


  • @Jeff

    No, but you can do this:


    Mapper.Map(someDogArrayOrListOrAnythingIEnumerable, typeof(Dog), typeof(Cat)) => returns a Cat[] (never null)

    I just don’t have a way to do it with generics….but it’s probably a great idea, supporting a generic way of making an array.

    You could try Mapper.Map(dogArrayOrWhatever), that might work.

  • Josh Schwartzberg

    Is there a way to ignore/exclude properties from the mapping? Would also be cool if we generated a proxy class so we could lazy load the properties.

  • @Josh

    On the first point, yes, there’s an “Ignore()” option for a member mapping.

    CreateMap().ForMember(x => x.Blarg, opt => opt.Ignore());

    On the second, do you have a scenario in mind where lazy loading/deferred execution is needed, and you want to come out of a Map operation with not all the data there?

    Usually, I design each DTO specifically for each need, not much reuse.

  • huey

    I had always wondered if I was missing the point of DDD when doing object-object mapping. Glad to see it is common :)

  • I’m still missing the point – I don’t understand why reusing the domain model to populate the presentation layer is a bad thing. I just posted on StackOverflow about this — — can someone please help me to fill in the blanks?

  • @bogardj

    It would be nice to have the option of naive two-way binding. It could always be overriden for special scenarios. In keep my validaiton in my domain model so my mappings tend to be equally simple in both directions.

  • @Liam

    To be honest, we just haven’t needed it yet. We’re moving towards a paradigm of entities updating themselves from messages. I do see the need, maybe an email with conventions/scenarios you’re looking for? Even a failing unit test would be flippin’ awesome :)

    Our entities were just too complex to be bound from messages, with complex collection operations, value objects, local entities, etc. There really wasn’t a “convention” around being able to populate our model, nor did we want one, the names and operations needed to come from the ubiquitous language.

  • Can you map from a Request.Form collection to an object with the mapper ?

  • @Erik
    I don’t personally have a huge problem with using the model directly to populate view pieces, but from my experience the pain isn’t generally with meshing a conceptual difference in view/model data or representations, but rather from dealing with issues like null checks, and the data type discrepancies (i.e. using a bool vs. outputting “Yes” or “No”). Having a view object that just has strings as fields makes the view so much cleaner to look at, and simple to work with too. Dealing with the same translation crap over and over again is just a PITA to deal with all the time, and this is a solution to that problem.

    I can honestly say, having worked on a project that used the Automapper, that it’s a pain to think of starting a project that didn’t have it.

  • You have an Initalize method – it should be Initialize.

    I have a mapping that’s missing a couple of fields – how do I tell it to add those? (That is, the source has fewer fields than the ViewModel – I know how to instantiate the missing fields, but how do I tell that to the mapper?)

    Thanks for the project, it was annoying to do this by hand :)

  • @Steve

    I’d have to hear more about your situation, but you’d probably want to use a different mechanism to do so, such as MVC’s ModelBinder. Right now AutoMapper supports only no-arg methods and properties on source types.

  • @Marcel

    To do that, use a custom value resolver. Just create a class that implements IValueResolver, then tell AutoMapper to use it for that one field.

    ForMember(m => m.Foo, opt => opt.ResolveUsing())

  • Hallgrim

    We needed mapping from List to List, so we checked out the sourcecode and made something that seams to work fine. It actually supports mapping from IEnumerable to List if there exist a mapping for the source element type and . Maybe you could use our results? Maybe you can do it more generic too, like support IList and ICollection or something?

    We added a new test in the Map method:
    private object Map(ResolutionContext context) {

    else if ((context.DestinationType.IsGenericType && (context.DestinationType.GetGenericTypeDefinition().Equals(typeof(List<>).GetGenericTypeDefinition()))) && (context.SourceValue is IEnumerable))
    valueToAssign = CreateListObject(context);


    Here’s the code based on the CreateArrayObject method in the MappingEngine.cs class:

    private object CreateListObject(ResolutionContext context)
    IEnumerable enumerableValue = ((IEnumerable)context.SourceValue).Cast();

    Type sourceElementType = GetElementType(context.SourceType);

    Type destElementType = context.DestinationType.GetGenericArguments()[0];

    var dstList = (IList)Activator.CreateInstance(context.DestinationType);
    int i = 0;
    foreach (object item in enumerableValue)
    Type targetSourceType = sourceElementType;
    Type targetDestinationType = destElementType;

    if (item.GetType() != sourceElementType)
    TypeMap itemTypeMap = Configuration.FindTypeMapFor(sourceElementType, destElementType);

    targetSourceType = item.GetType();
    targetDestinationType = itemTypeMap.GetDerivedTypeFor(targetSourceType);

    TypeMap derivedTypeMap = Configuration.FindTypeMapFor(targetSourceType, targetDestinationType);

    var newContext = context.CreateElementContext(derivedTypeMap, item, targetSourceType, targetDestinationType, i);

    object mappedValue = Map(newContext);



    object valueToAssign = dstList;
    return valueToAssign;

  • Hallgrim

    One more note.

    With the new method we created you only have to configure mappings for the element types. Like this:


    You DON’T need to specify it like this:
    Mapper.CreateMap , List>();

  • @Hallgrim

    Awesome. I’m setting up an AutoMapper-users group, but I’d love to get a patch on this one. Can you contact me through the blog above? Thanks!

  • matt

    For enum mapping support would I be looking at writing a custom resolver or is that supported as well? How do you typically handle those?

  • Hallgrim

    Patch for List support uploaded to the AutoMapper-users group

  • @matt

    If you could, would you mind putting up some mapping that doesn’t work up on the AutoMapper users mailing list? Or better yet, a failing unit test. It’s easier if I have a scenario with code to look at, as we’re doing quite a bit of Enum mapping in our codebase.

  • matt


    Sure thing – I’ve got a test fixture prepared – I’ll send it to the list. Thanks!

  • Hi,

    Initially, I’ve got the same needs as yours (mapping object to data contracts of WebServices is really boring and error prone). I was searching for an Object-to-Object Mapper, I do not find it in .NET community, so have a look at Java community and found “Dozer”.
    Then, I make some search and find some interesting posts giving some start points to implement it. I have started, wanted to publish it on CodePlex and finally do not have time. I think it would be interesting to share my work with you (it would be ridiculous to make two different tools I think).

    That’s something we talk about in a Paris meeting. And I see that there are other needs for this type of tool (dynamic mapping).

    I have started a post on my “starting” blog, but I would like to detail it a bit before publish. Keep an eye.


  • @Clement

    Sounds good, I’ll keep an eye on it!

  • Martin Nyborg

    The mapper returns a new object and for 99% of the cases this is god.

    like this:
    RamsiteDTO = Mapper.Map

    But the DTO object has a lot going on in the property setters like NotifyChange and validations rules and I need to create the object first to bypass this checks.

    var RamsiteDTO = new RamSite();
    using (RamsiteDTO.BypassPropertyChecks)
    (ramsite, RamsiteDTO);

    Is this possible?

    I have also posted this on Codeplex

  • I’m really surprised there doesn’t seem to be any support at all for auto-mapping fields. (Public fields on DTOs make for cleaner messages when using the DataContractSerializer.)

  • Hi Jimmy

    I’ve tried after a few Hello World-examples to implement mapping between a source DataRow object and a target Person-object – I guess it will be possible to do it with a class implementing IValueResolver but I haven’t tried it out yet (is it possible?).

    However – if you retrieve a DataTable with tablecolumns named i.e. ID, Name and Adress from your database it would be awesome to have the conventionbased rules engine to check for matching property names in the target object if the source is i.e. a DataRow or an equivilant data carrier. Will you consider the following scenario for a future release?

  • @Pat

    No, not yet. That would be easy to do, however.

  • Jimmy, re: field mapping, Easy yes, trivial no. Tragically, PropertyInfo and FieldInfo, despite sharing large portion of their API, don’t share a common root. That means that for AutoMapper to support field mapping I think it would require creating a common interface, like IPropertyInfo, a wrapper that implements that interface and that can contain an inner Member info and treat PropertyInfo and FieldInfo the same, and touching all the places in the AutoMapper code that use PropertyInfo to replace them with IPropertyInfo, and of course everywhere that talks directly to the .NET reflection system would need to be have a shim inserted as well. This could all be accomplished in a few hours, but if we were to make those changes, what are the chances they could be included in the project? If that is unlikely, what are the chances this functionality will naturally evolve out of AutoMapper?

  • Never mind – I went ahead and made the changes and uploaded them as a patch (created using tortoise – never done that before, hope it is useful) to the Codeplex site. The patch includes two sets of tests, copied from existing tests but using fields instead of properties.

  • @Nathan

    I was in the process of adding it myself, but a patch works just as well! Thanks!

  • What a fast response! Awesome! Love the tool BTW. We are currently working on two ends of a messaging system, using a hand mapping process on the one end to go from entities in one source system to common DTO’s, and evaluating AutoMapper on the other end, going from DTO’s to a different breed of entities, and AutoMapper makes for a nice clean mapping layer when you compare the two side by side.

  • Xsword

    Would you like to see NBear.Mapping in
    The project in CodePlex is

  • Xsword

    Would you like to see NBear.Mapping in
    The project in CodePlex is

  • Xsword

    Would you like to visit the project NBear(
    The project is also in codeplex(
    The nbear.mapping component is design for DataSet < -> object and object < -> object.Thank you.

  • Can we get some examples of how ot use AutoMapper?

    i.e.what are all the methods available and when to use them. Also how to meet this never null requirement?

    mainly I’m getting a compiler error trying to use the AutoMapper to map from an IEnumerable to IEnumerable ( why does it have to be an Array?? I need to transform the results if necessary and do not want to be converting back and forth.

    I have a simple IMapper that already does this here is the signature if you could help clarify which Automapper method could best accomplish this it would be appreciated:

    public static IEnumerable MapAll(this IEnumerable input, IMapper mapper)

  • @Confused

    Can you do me a huge favor? Would you mind reposting this on the AutoMapper mailing list? That way, if anyone else is interested in these questions, they can get the answer too :)

  • espinete broken link !!! thanks

  • Just so you know, this is one of the awesomest pieces of awesome we have put to use in my office in the past year. Thanks for a great tool!

  • codeplex link is still down. has it been moved elsewhere?

    kind regards,

  • Marvion

    Hi, Very useful tool.
    But i have a question.
    does this run slower than manual entity mapping or not?

  • @Marvion

    Yep, it runs slower. You trade less code and a more powerful tool for the speed. However, it’s not much slower from the numbers I’ve run, and is very far from the bottleneck in our apps we use it on.

  • JOe

    Will automapper work with a type that does not have a parameterless constructor? If not,would it be possible to pass in a delegate to return a new instance of the type when you register it?


  • @Joe

    Yes, there is a ConstructedBy method that accepts a Func for custom construction of the destination type.

  • Jimmy,

    I am trying to use automapper in IIS 7 with signed assemblies and it chokes with a “Request Failed” error. Prior to finding your post here I posted a detailed explanation and request for help on stackoverflow. (

    Could you take a look and tell me if I am doing something wrong or if there is a compatibility problem? Not being able to use AutoMapper in IIS7 is killing us.


  • Sanjay

    Hi, Here are my concerns

    The Automapper only maps if the Source and the Destination properties which share the same name. for instance i will not be able to map CustId with CustomerId

    It does even map nullable dataTypes properly – if the value
    is provided as Null – It maps and puts the value as an empty string or zero in case of Nullable Int.

    Works fine with complex datatypes- Not sure how will it behave if the class is nested.

    Guess, the next version should use some kind of refelection methodologies to map accordingly

  • Sanjay


    Hi Juimmy, Here are my concerns

    The Automapper only maps if the Source and the Destination properties share the same name. for instance i will not be able to map CustId with CustomerId

    It does not map nullable dataTypes properly – if the value
    is provided as Null – It maps and puts the value as an empty string or zero in case of Nullable Int.

    Works fine with complex datatypes- Not sure how will it behave if the class is nested.

    Guess, the next version should use some kind of refelection methodologies to map accordingly

    Thanks & Regards
    Sanjay JDM

  • @Sanjay

    Could you post these issues on the google group? Thanks!

  • Test is looking good:

    – code –
    // Prepare
    Mapper.CreateMap< Gallery, GalleryVm >( );
    Mapper.CreateMap< Album, AlbumVm >( );
    Mapper.CreateMap< Slide, SlideVm >( );

    Slide slide = new Slide{Title = “I’m a slide” };
    Album album = new Album{ Title = “I’m an Album”, Slides = new List< Slide >{ slide } };
    Gallery gallery = new Gallery{ Title = “I’m a Gallery”, Albums = new List< Album >{ album } };

    // Act
    GalleryVm vm = Mapper.Map< Gallery, GalleryVm >( gallery );

    // Assert
    Mapper.AssertConfigurationIsValid( );
    – end code –

    Q: In a large solution (100+ projects), will the auto mapper be able to live? It seems like it’s storing all the maps statically? (I haven’t downloaded it’s source yet)

    Q: Is this using reflection, or are the maps generated during compile time?

    Looking awesome otherwise, simply awesome!

  • @pedro

    100+ projects???!?! I think you’ll have other issues before Automapper becomes your problem.

    It actually uses reflection.emit to perform mapping, Configuration is done once per app domain.

  • I’m a consultant, the 100+ projects are my customers work. Unfortunately, I have to relate to them, and try to make them better. Automapper would go a long way in refactoring the app :)

  • Good one.. very useful..

  • Andrei Sedoi

    Hi Jimmy,

    I am excited of your project. It really helps a lot.
    Nevertheless, I can’t still use it in my project because of the issue in the AutoMapper.Configuration.FindTypeMap(object, Type, Type) method. I have added the issue here

    I would appreciate it very much if you could fix this issue asap so that i was able to start using AutoMapper library in my project.


  • Chingo Bling in San Anto

    “I would appreciate it very much if you could fix this issue asap so that i was able to start using AutoMapper library in my project.”


  • I think you might be getting your terminology wrong. What you refer to as a POCO is actually a DTO (data transfer object). A POCO is usually used to describe objects that are free from persistence information. For instance, the auto-generated classes you get from Linq to SQL are NOT POCOs, because they have persistence logic within them.

  • ranu mandan

    is there a configuration file required for mapping objects ?

    • Anonymous

      No, there’s not.

  • AutoMapper tries to map all properties of the source type to the destination type. If some of the properties are not available in the destination type it will not throw an exception when doing the mapping.

  • Pingback: Chris Currie » Blog Archive » Use AutoMapper to Map ViewModels to Entities – MVC3 and Razor()

  • Pingback: Is there an automap solution for this ETL code?()

  • How do i get a Wave Mapper on my computer so i can record audio coming through my speakers?

  • bagonlineretail bagonlineretai

    good[url=]iphone 4s sale[/url]  [url=]iPhone 4s book[/url]  [url=]iPhone 4s preorder[/url]  [url=]iphone 4s unlocked sale[/url]  [url=]iphone 4 sale[/url]  [url=]cheap iphone 4 for sale[/url]  [url=]apple iphone 4 sale[/url]  [url=]iphone 4 clearance[/url]  [url=]buy ipad 2 online[/url]  [url=]ipad 2 best buy[/url]  [url=]Ipad 2 clearance[/url]  [url=]apple macbook sale[/url]  [url=]apple macbook black[/url]  [url=]apple macbook white[/url]  [url=]apple ipod[/url]  [url=]apple ipod sale[/url]

  • How do i get a Wave Mapper on my computer so i can record audio coming through my speakers?

  • i am having problem with my transcend external hard disk it showing that unable to mount exit code 13 error?

  • Joe Daigle

    Ive been using AutoMapper for a while now, and have to say that I love it – thank you so much for brainstorming, following through and finally releasing it to the world. Well done!

    Couple of questions please -
    1) Im using it mostly for copying to/from EF CF entities in my repository layer, where I have lots of (readonly) navigation properties.  I want to copy these properties up to my domain model during a retrieve/get operation, but not back down since they arent direct attributes of the EF entity itself.  I seem to have to do a opt.Ignore() for all of these in the DomainEntity->EFEntity direction.  Any way to have automapper deal with this automatically?
    2) Id like a “using” type ability, where I can tell Automapper to look in this particular child entity if it needs to map something and cant find it in the object itself.  Dumb idea?  :-)

    Thanks again Jimmy, Automapper absolutely rocks!

    • Anonymous

      Funny, we were just working on the first one today! But for us, it was in MVVM land, going DTO->VM, where you want validation to be based on the *source* members.

      If you check out the latest download from, there’s an overload for CreateMap that lets you specify the member list you want to validate against (source/destination).

  • Pingback: AutoMapper doesn’t work for mismatched types | Yen's Blog()

  • Sebastian Castaldi

    can I map a datatable? something like…

    Mapper.CreateMap<IEnumerable, List>();
    var dt = TriggerEngineModel.GetHistory().Select().ToList();
    var viewModel = Mapper.Map<IEnumerable, List>(dt);

    • Anonymous

      No, not right now.

  • Daniel Fabia

    is it possible to pass an instance of the target object? Mapper.Map return new instance of the target type.

    • There’s an overload to Map that you can pass in an instance of the destination object, use that one.

  • Pingback: Data Annotations and ViewModels | Ian Tipson()

  • Vikas Nigam

    Exactly what I was looking for my first open source enterprise .NET app. Had almost given up and started to write my own little library for mapping objects.. You saved me days of hard work, testing etc. :)

  • burak

    a little bit late question but i wonder if you followed up any design pattern/s while you were developing automapper?

    • jbogard

      No, not really, but I could though!

  • Eileen

    Hi Jimmy, I really want to use Automapper, can you help me solving this problems?

  • Eileen Qian

    Hi Jimmy, can you help me with this problem? Much appreciated!

  • Maheshwaran

    Useful and did help save lots of time fixing my probelm.

  • Nikhil

    Hi Jimmy,

    I am not sure whether question which I am going to post is previously being asked or not !! Still, Is it possible to intercept auto mapper mapping?

  • disqus_LoskbgXPfp

    Is there a way I can map 2 list objects.Example: Mapper.Map<IList, IList>(lst);

    • jbogard

      Yes, just create a map for Employee1 -> Employee2. AutoMapper automatically supports lists.

  • Pingback: AutoMapper and mapping Expressions | Ahmadreza's Notes()

  • meantraveller

    I would also take a look at Supposed to be astonishilgly fast. And very simple to use.