Pages

Friday, March 16, 2012

Copying data between classes with Automapper

Sometimes you have similar classes in your project and you want to copy data from one instance of a class to another. In my old days I used to do that myself going field by field. That was until someone told me about Automapper.

One of the situations where you might want to copy data from one instance of a class to another instance of another class if for example when you expose Entity Framework classes through a webservice.

Entity Framework classes by default have more information that is sort of irrelevant for business needs when serialized. So, if I have a Workers table in my database. Each worker with Id, Name, Address and Phone Number, and  I create a service that returns a list of workers, I might end up with an xml response that looks something like this:

(Click on image to enlarge)
And you can see the presence of nodes by the name of EntityKey, EntityContainerName, EntityKeyValue and so on, which are the result of your class being generated by the Entity Framework.

One thing you can do is create your own Plain Old CLR Object (Poco) version of the Worker class, without any attributes only those necessary for serialization in the WCF service:

(Click on image to enlarge)

And then you can use Automapper to easily convert your Entity Framework Worker class to a Poco Worker. Let's implement a method where you hit the database via the Entity Framework to select a list of workers and then you convert the whole list to a list of Poco Workers before the output of the result:

(Click on image to enlarge)


And invoking that method in a WCF service results in a friendlier output:

(Click on image to enlarge)

At the bottom of the article you can download a sample project of a WCF REST service with two methods that illustrate this:
- GetEntityFrameworkWorkers, which returns a list of Entity Framework Workers
- GetPocoWorkers, which uses Automapper and returns simpler Workers objects. Generating a cleaner xml output.

I wanted to keep it simple in this case and created the Poco Worker with the same property names as the Entity Framework one. In the practice you may have different property names, and in order to do the conversion you will need to provide Automapper with more details in the mappings of the objects.

Download source code




No comments:

Post a Comment