LINQ provides a Distinct() method, but in order to find distinct elements in a list of some target class, we must first implement the IEqualityComparer<T> interface in our target class. That’s what Distinct() uses in order to compute whether one element is the same as another element. Implementing IEqualityComparer<T>, however, is not so straightforward as it requires us to override Equals() and GetHashCode() methods. Most of the times if all we need to do is just to find non-duplicated elements in a given list, IEqualityComparer<T> route seems like an overkill. Read more…
I just released a new version of open source Texticize. Texticize is an extensible and intuitive object-to-text template engine for .NET. You can use Texticize to quickly create dynamic e-mails, letters, source code, or any other structured/unstructured text documents using predefined text templates substituting placeholders with properties of CLR objects at run-time.
AutoMapper is an awesome open source library that allows automatic object-to-object mapping. There are various getting-started blog posts and articles on the web (e.g. Getting Started Guide and AutoMapper on CodeProject) that will get you started with AutoMapper. I was recently challenged with a particular situation using AutoMapper that wasn’t immediately clear and took me a little investigating and some trial and error work, so I will share that with you.
My source object exposed some simple properties as well as a generic List property of another type. My target object had same simple properties, but the generic List property was of an interface type. Following is a simplified illustration of my source and target objects:
Source Object
Target Object
A cool thing about AutoMapper is that when it encounters a target object of an interface, it automatically generates a dynamic proxy class using Castle Dynamic Proxy. This is usually the desired behavior when mapping to a non-existent target class. In my case, however, the target class already existed, and dynamic proxy was just an overhead. I tinkered with AutoMapper mappings to actually map to my existing target rather than generating a proxy:
Essentially what I am doing in my mapping is to first create a map between my source and target Orders objects. Once that’s done, I create a map between my source and target Customer objects but provide a custom map for the Orders property. In my custom map I simply use AutoMapper to map my source Orders property to target Orders property using the map definition I provided earlier (lines 1-2 above). This works out great and I get my expected target object without incurring the overhead of expensive proxies.