Here’s a simple implementation of an object mapper using lambda expressions that I’ve shown yesterday at the Tulsa School of Dev. Say we need to copy some data from one object to another. For this example my objects are a Book and an AlternateBook. The class are shown below:
public class Book { public Book() { } public Book(string title, int yearPublished) { Title = title; YearPublished = yearPublished; } public string Title { get; set; } public int YearPublished { get; set; } public string AuthorFirstName { get; set; } public string AuthorLastName { get; set; } } public class AlternateBook { public string AuthorFullName { get; set; } public string Title { get; set; } }
I could have a mapper that worked like this:
Mapper mapper = new Mapper(book, alternateBook); mapper.AddMap("Title", "Title"); mapper.AddMap("AuthorFirstName", "AuthorFullName");
That approach would have some problems, though:
- The properties are mapped using string literals, which means we don’t benefit from strong-typing or IntelliSense (bugs could easily arise because of typos or properties that don’t exist on the objects);
- The properties have a 1:1 mapping, which in the sample above wouldn’t really work, since I had to map "AuthorFullName" directly to "AuthorFirstName", as oppose AuthorFirstName and AutorLastName.
- The mapper would have to use Reflection to look up the properties on the given objects and then assign their values (not the most optimized way of doing it…).
The approach using Lambda expression would look like this:
var mapper = new Mapper<Book, AlternateBook>(); mapper.AddMapping((b, ab) => ab.Title = b.Title); mapper.AddMapping((b, ab) => ab.AuthorFullName = b.AuthorFirstName + " " +
b.AuthorLastName);
Points to note:
- As I instantiate the Mapper I provide the type of objects as Generic parameters;
- The AddMapping method takes in lambda expressions that receive two parameters (b and ab, for book and alternate book, respectively), which I then use to set the mapping. That gives me both strong-typing and IntelliSense support.
- The lambda expression also opens up control over how things are pushed into the target object. In the sample below, I can format how the alternate book’s AuthorFullName property gets populated;
- Since the lambda expression is compiled down to a delegate, there’s no Reflection involved, so the code should run faster when executed.
Now, in case you’re not familiar with lambdas yet: the expression does NOT get executed when we are passing it as a parameter to the AddMapping method. At that point we are only registering the m apping; the actual execution occurs whenever we want it to. I would probably, say, at the application start, register all mappings I’m likely to use. Eventually, when I need to actually process the mapping (copying some data from one object to another), I can just call the ApplyMapping, passing in the objects involved with the mapping. For example:
Book book = new Book { AuthorFirstName = "Claudio", AuthorLastName = "Lassala", Title = "Some book" }; AlternateBook alternateBook = new AlternateBook();
mapper.ApplyMappingsTo(book, alternateBook); Console.WriteLine( "Book:"+ "\r\n Title: "+ book.Title + "\r\n AuthorFirstName: " + book.AuthorFirstName + "\r\n AuthorLastName: " + book.AuthorLastName); Console.WriteLine( "\r\nAlternateBook:" + "\r\n Title: " + alternateBook.Title + "\r\n AuthorFullName: " + alternateBook.AuthorFullName);
The code above should produce the following results:
So, how’s the Mapper class implemented? Here we go:
public class Mapper<TSource, TTarget> { private Collection<Action<TSource, TTarget>> m_Mappings = new Collection<Action<TSource, TTarget>>(); public Collection<Action<TSource, TTarget>> Mappings { get { return m_Mappings; } } public void AddMapping(Action<TSource, TTarget> action) { Mappings.Add(action); } public void ApplyMappingsTo(TSource source, TTarget target) { foreach (var mapping in Mappings) { mapping(source, target); } } }
The class keeps a list of all the mappings within its Mappings collection, which is a collection of Action<TSource, TTarget> delegates. Both TSource and TTarget are Generic types provided to the class. The AddMaping method takes in the delegate (which we pass in as a lambda) and adds it to the Mappings collection. The ApplyMappingsTo method takes in instances for the source and target object, iterates through the Mappings collection, and invokes each mapping (don’t forget it, the mapping is a delegate).
That’s it. Again, this is just a simple implementation. I’m pretty sure there’s a lot of improvements to be done on top of this, and there’s definitely something some people wrote out there around the same lines; I’ll be looking for that myself in order to see how I can improve this.
For instance, one thing that pops up is: what if the developer messed up and specified the mapping going from the target to the source instead? Like so:
mapper.AddMapping((b, ab) => b.Title = ab.Title);
We certainly don’t want to copy the title from the Alternate Book to the Book object. I don’t know of way yet to have the compiler catch that problem (any ideas?). During runtime, though, I know I could have the AddMapping method analyze the Expression Tree for the lambda it was given, and make sure that the target appears at the left side of the = sign, and the target appears at the right side.
Another improvement that could be made is some optimization. For instance, itake the following code snippet:
mapper.AddMapping((b, ab) => ab.AuthorFullName = b.AuthorFirstName + " " +
b.AuthorLastName);
There, the developer has used string concatenation to build up the value to be assigned to the property. The AddMapping method could have some logic that analyzes the expression tree, and if it finds something like string concatenation, it could replace that with using a StringBuilder. Of course, such optimization should only be done if we can clearly see that as being something that we really needed to squeeze better performance out of.
Also, it’d be convenient to have the mapper just figure out what properties to copy from the source to the target by looking for properties that map 1:1 (that is, property name and type exist on both objects), and then let the developer only supply special mappings for properties that require transformation.
I’ll be doing some more research on better ways to do this kind of stuff.




Leave a Reply to claudiolassalaCancel reply