Thursday, June 4, 2015

AutoMapper with C#

Intro

Our world is a cold, cruel place where mapping the properties of one type to the properties of another type is a tedious chore, best left to bleary, dreary late night work while buzzed on enough caffeine to bug-eye a rhino. But wait, what light yon winder breaks? or something...


AutoMapper! If you guessed that AutoMapper is a new way to create your own maps from within a car, you'd be wrong! AutoMapper is a NuGet package that you can use in .Net to map the properties of one type to the properties of another type. If for example you have a middle-tier Person class that needs to map to a backend database class called PersonDb, AutoMapper can take most of the tedium away from you. No more setting Person1.FirstName = Person2.FirstName, yadda yadda. All you have to do is make a single call to initialize the configuration, make another call to map object 1 to object 2, and you're golden! Let's see it in action.

Note: Sample Project is in VS2013 Community Edition.

Samples

OK let's get movin. Create yourself a console application. You'll then need to install the NuGet package named AutoMapper. I'll show you a different way than I've used in the past, maybe you'll find this easier or maybe not. Anyways...


then in the Package Manager Console, type "Install-Package AutoMapper"...


OK now we've got AutoMapper installed in our console app. Add yourself a couple classes to the project, named Type1 and Type2. Here is the code for each: 


using System;

namespace BlogAutoMapper
{
    public class Type1
    {
        public string FirstName { get; set; }
        public int Age { get; set; }
        public DateTime DateBoughtFirstCar { get; set; }
    }
}


using System;

namespace BlogAutoMapper
{
    public class Type2
    {
        public string FirstName { get; set; }
        public int Age { get; set; }
        public DateTime DateBoughtFirstCar { get; set; }
    }
} 

Pretty simple stuff here.Now let's use AutoMapper. First open up your Program.cs file and add a "using AutoMapper;" statement up in the using statements. Now plug the following code into your Main method:

using System;
using AutoMapper;

namespace BlogAutoMapper
{
    class Program
    {
        static void Main(string[] args)
        {
            var type1 = new Type1() { Age = 44, DateBoughtFirstCar = DateTime.Parse("01/01/2000"), FirstName = "Perriwinkle" };
            Mapper.CreateMap<Type1, Type2>();
            var type2 = Mapper.Map<Type2>(type1);
            Console.WriteLine("type2.DateBoughtFirstCar: " + type2.DateBoughtFirstCar.ToShortDateString() + "...type2.Age: " + type2.Age + "...type2.FirstName: " + type2.FirstName);
            Console.ReadKey();
        }
    }
}

That's it! If you had 10, 20, or even 50 properties, it would map them for you. Pretty handy huh? Here's what the output loooks like, just to prove it does what it says it does:



What's Next?

AutoMapper has a ton more features. I've shown you only the very basics. It can handle copying lists of objects, it can hit up sub-objects, you can customize the value copying (note how right now the source and destination properties have to be the same name), you can make it look at private member fields, and so much more. Play around with AutoMapper and see what it can do for you. I wonder if it could be used as a poor man's object cloning, hmm...

Resources

AutoMapper
Keith Durham: Thanks for pointing out this gem to me sir!

No comments:

Post a Comment