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:
- UserEntity.Id -> UserDTO.Id
- UserEntity.UserName -> UserDTO.TheUserName
- 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();This allows me to do a one-way mapping from the UserEntity to the UserDTO.
cfg.AddAssemblyResources(Assembly.GetExecutingAssembly(), "otis.xml");
IAssemblerdtoFromEntityAssembler = cfg.GetAssembler ();
UserEntity entity = new UserEntity(5, "Bob Dole", "bdole");
entity.Advisor.Name = "sdaddds232";
UserDTO dto = dtoFromEntityAssembler.AssembleFrom(entity);
Hi Colin,
ReplyDeletei 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