Wednesday, February 06, 2008

Object-Object Mapping

We're starting to do a lot of mapping between domain classes and other forms, so far mainly so that we can export representations of our domain objects to external systems.

Performing the mapping quickly becomes a real pain and testing the mappings is even worse.

I don't think there is much you can do about the dullness of the testing, but I have been looking for a framework that will make the mapping easier and on an ALT.NET thread on the topic someone suggested I look at a little library called Otis.

So far I'm very impressed so here's what I've found. If you want to know more download the binaries or source code, the advantage of the source code is that it has a sample with it. The WIKI also has good information but I wanted to write what I've found so far, mainly to remind myself.

Mapping Files

I think I'm going to use the XML file approach as its cleaner, I've name the files "*.otis.xml" and made them "Embedded Resources". I also setup the XSD that you get with the binaries to give me intellisense which is very useful.

Lets look at a simple example:This shows the following:

  1. UserEntity.Id -> UserDTO.Id
  2. UserEntity.UserName -> UserDTO.TheUserName
  3. UserEntity.Advisor -> UserDTO.Advisor.Name

As you can see the mapping is written from the standpoint of the source class, once you get this its quite easy to follow.

You can read more about the mappings here but the sample with the source code is also good.

Configuration

To get the same to work I had to using the following C# code:

Configuration cfg = new Configuration();
cfg.AddAssemblyResources(Assembly.GetExecutingAssembly(), "otis.xml");

IAssembler dtoFromEntityAssembler = cfg.GetAssembler();

UserEntity entity = new UserEntity(5, "Bob Dole", "bdole");
entity.Advisor.Name = "sdaddds232";

UserDTO dto = dtoFromEntityAssembler.AssembleFrom(entity);
This allows me to do a one-way mapping from the UserEntity to the UserDTO.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

1 comment:

  1. Hi Colin,

    i am glad that you find otis useful. If you have any suggestions how to make it more usable, don't hesitate to send them to me or post them here (or even better, here: http://code.google.com/p/otis-lib/wiki/OtisRoadmap).

    zdeslav

    ReplyDelete