BestPractice: pros and cons for using AutoMapper or LINQ (LINQ to Objects) to map between domain model and presentation model
Quoting part of the answer from another question by Automapper :
If you have an object of one type and want to populate the properties of an object of a different type using the properties of the first type, you have two options:
- Manually write the code to make this mapping.
- Use a tool that will automatically handle this for you.
AutoMapper is example 2.
LINQ to Objects Example 1 is just a little painful than writing object-to-object mapping code.
In terms of pros and cons:
-
Automapper should dramatically reduce the amount of code you have to write compared to LINQ because it uses conventions to define default mappings. Using LINQ, these mappings must be defined by default.
-
Using LINQ it will be necessary to define mappings in both directions - Automapper should be able to work automatically when conventions are used.
-
As with all third party dlls, using Automapper will result in a different dependency and require a small learning curve (note that there would be a learning curve for those developers who have not used LINQ before).
Note. Automapper can be used in conjunction with LINQ (and LINQ2SQL) - another Automapper post that explains some of the finer points.
a source to share
http://bhavinsurela.com/linq-and-automapper-view-model-and-data-model/ might be what you are looking for.
a source to share
There are also disadvantages to using AutoMapper, and some of these disadvantages usually apply to programming by convention (as opposed to writing code explicitly).
Let's 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; }
}}
AutoMapper will map between these two classes nicely with little explicit configuration.
But later, let's say the developer considers renaming one of these id properties to something else, for example.
namespace MyBusinessLayerNamespace {
public class MyClass {
public int MyNewIdentifierVariableName { get; set; }
}}
I look carefully for references in Visual Studio and look at the effect of renaming on those references, but since MyDtoNamespace.MyClass.Id does not explicitly refer to MyBusinessLayerNamespace.MyClass.Id, I never see it.
When Visual Studio or another tool automatically renames all occurrences of a variable for me in the solution, the AutoMapper display breaks.
I can only find out this at runtime, no compile time issue. Ideally, I have unit tests to see if my mapping works, but the potential for errors during refactoring is nevertheless a good reason to prefer writing explicit conversion code.
I'm certainly not arguing to avoid AutoMapper altogether, just pointing out that the underlying problem is with convention programming.
a source to share