AutoMapper is a great, free library available for .NET and accessible through nuget. It allows you to map and copy property data from one class to properties of another class. It does all of this based on naming convention.
Assume that we have the following the two classes:
class first
{
public string A { get; set; }
public string B { get; set; }
public string X { get; set; }
}
class second
{
public string A { get; set; }
public string B { get; set; }
public string Y { get; set; }
}
If we tell AutoMapper to map from an instance of class first to an instance of class second it will automatically copy the data stored in the public properties A and B from the first class into the second class. Properties Y and Z will not match, and therefore not be copied between the two classes. How does it do this? AutoMapper uses type reflection to automatically match the names of properties in the source class to the names of properties in the destination class.
This technique has many applications, and is available to save countless hours of mapping code. This can even be used to map properties of LINQ to SQL or Entity classes to allow for shallow copying of one object to another. Another application is for creating projection classes for use by an outside method.
How does it work? AutoMapper must be configured with knowledge about which classes to match. This must be done once per Application Domain.
Mapper.CreateMap<first, second>();
Mapper.AssertConfigurationIsValid();
For web applications it is suggested that this mapping be done in the Application_Start method of your Global.asax.cs or Global.asax.vb file. This will ensure that the mapping is only run once per domain. Now that we have told AutoMapper how to map, let’s tell AutoMapper to map something.
var fInstance = new first();
fInstance.A = “hello”;
fInstance.B = “world”;
var sInstance = Mapper.Map<first, second>(fInstance);
Console.WriteLine(sInstance.A + ” ” + sInstance.B);
The output of this application would be “hello world”. AutoMapper would copy the properties in first_instance.A and first_instance.B to a brand new instance of the second class.
At this point, if you tried to compile and run the application, you might be wondering why you are getting an exception. AutoMapper is unable to map first.X to first.Y, and therefore throws an exception. You can force AutoMapper to ignore a column when you creating your mapping using a lambda expression.
Mapper.CreateMap<first, second>().Ignore(a => a.X);
When you run the application again, AutoMapper will ignore that column and your output will be as expected. What happens when there are many columns you wish to ignore? Writing a lambda expression for each column would be tedious. Luckily somebody over at stackoverflow has come up with a handy extension method which you can use to ignore all columns which don’t match.