tags:

views:

753

answers:

5

I've used plenty of ORM tools in the past, NHibernate, .netTiers, LLBLGen and more and they always do a pretty good job of mapping data from a database to objects in code.

What I'm looking for though is a framework or a pattern or something that will allow me to transform objects from one type to another.

An example is I have a two web services, one has Investors another has Members. I want to convert an Investor object to a Member object by defining a set of rules that maps the Investor properties to the Member properties and back again.

NHibernate mappings are the closest I can get to doing this, but it only seems to work for Database -> Object mappings. I was wondering if anyone knew of any products that allowed me to do obejct -> object mapping?

+2  A: 

You can use .NET Serialization to serialize one type to another provided they share a common contract.

MSDN has a lot of good info:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.aspx

Specifically, DataContractSerializer.

FlySwat
Completely different thing.
Alex Yakunin
+3  A: 

Jonathan mentions data-contracts, which is a good option. I guess part of the reason that there isn't massive support for this is that it is already fairly easy to do through code, for example via a conversion operator (although a regular instance method would work just as well, and arguably be clearer) ...

class Foo {
    public string Name { get; set; }
    /* etc */
}

class Bar {
    public string Caption { get; set; }
    /* etc */

    public static explicit operator Foo(Bar bar) {
        return new Foo { Name = bar.Caption /* etc */};
    }
    public static explicit operator Bar(Foo foo) {
        return new Bar { Caption = foo.Name /* etc */};
    }
}

If you don't control the classes (and partial classes aren't an option), then in C# 3.0 you could use an extension method to simulate an instance method:

public static Foo ToFoo(this Bar bar) {
    return new Foo { Name = bar.Caption /* etc */};
}
public static Bar ToBar(this Foo foo) {
    return new Bar { Caption = foo.Name /* etc */};
}
Marc Gravell
+3  A: 

You are looking for AutoMapper

http://automapper.codeplex.com/

Matt Hinze
I'll definately be checking automapper out
lomaxx
+3  A: 

There is the Otis project that is similar to AutoMapper but it does its thing using attributes.

Keivan
Automapper looks better since its strongly typed rather than using string literals.
Keivan
+1 for mentioning an alternative.
tobsen
+2  A: 

Take a look on http://emitmapper.codeplex.com It faster and more flexible than automapper.