score:4

Accepted answer

Quoting part of an answer from another Automapper question:

If you have an object of one type and you want to populate the properties of an object of another type using properties from the first type, you have two choices:

  1. Manually write code to do such a mapping.
  2. Use a tool that will automatically handle this for you.

AutoMapper is an example of 2.

LINQ to Objects is an example of 1 - it just happens to be a bit less painful than writing vanila object-to-object mapping code.

In terms of pros and cons:

  • Automapper should significantly reduce the amount of code you have to write compared to LINQ as it uses conventions to determine default mappings. Using LINQ, these default mappings would have to be defined.

  • Using LINQ it will be necessary to define mappings in both directions - Automapper should be able to work this out automatically when conventions are used.

  • As with all third-party dll's, using Automapper will introduce another dependency and require a small learning curve (note there would be a learning curve for those developers who haven't used LINQ before as well).

Note, Automapper can be used in conjunction with LINQ (and LINQ2SQL) - yet another Automapper post which explains some of the finer points.

score:10

There are also disadvantages in using an AutoMapper and some of these disadvantages apply generally to programming by convention (as opposed to writing code explicitly).

Say you have two C# classes -

namespace MyDtoNamespace {
    public class MyClass {
        public int Id { get; set; }
}}

namespace MyBusinessLayerNamespace {
    public class MyClass {
        public int Id { get; set; }
}}

An AutoMapper will map between these two classes nicely with little explicit configuration required.

But later, say a developer considers renaming one of these Id properties to something different e.g.

namespace MyBusinessLayerNamespace {
    public class MyClass {
        public int MyNewIdentifierVariableName { get; set; }
}}

I carefully search for references in Visual Studio and consider the impact of renaming on these references - but because MyDtoNamespace.MyClass.Id does not explicitly reference MyBusinessLayerNamespace.MyClass.Id, I never see it.

When Visual Studio or another tool automatically renames all occurences of the variable for me in the solution, the AutoMapper mapping breaks.

I can only find this out at run time, there is no compile time problem. Ideally, I have unit tests to verify my mapping works as I hope but even so, the potential for run time errors during refactoring is a good reason to prefer writing explicit mapping code.

I am certainly not arguing to avoid AutoMapper altogether, just noting that a major problem with programming by convention.


Related Articles