woggles
woggles

Reputation: 7444

Automapper mapping 2 entities to a single class

Just wondering if this is possible:

Say I have a ViewModel for comparing an old and new entity.

public class FooComparison
{
public string Name {get;set;}
public string OldName {get; set;}
public int Age {get; set;}
public int OldAge {get; set;}
...
}

I want to load 2 instances of Foo from the database and populate the FooComparison with the details from both instances.

For now, I have Mapper.CreateMap<Foo, FooComparison>() which will populate the Name, Age etc from the first entity - is there an easy way to populate the Oldxxx properties from the second entity without looping and manually updating them?

Upvotes: 1

Views: 254

Answers (1)

Timothy Shields
Timothy Shields

Reputation: 79561

My suggestion would be to define a mapping from Tuple<Foo, Foo> to FooComparison:

Mapper.CreateMap<Tuple<Foo, Foo>, FooComparison>()
    .ConvertUsing(x => new FooComparison
    {
        Name = x.Item2.Name,
        OldName = x.Item1.Name,
        Age = x.Item2.Age,
        OldAge = x.Item1.Age,
        ...
    });

Then use it like this:

Foo oldFoo = ...;
Foo newFoo = ...;
FooComparison comparison = Mapper.Map<FooComparison>(Tuple.Create(oldFoo, newFoo));

I appreciate that this loses the "auto" part of automapper, but really the big benefit you are getting by using automapper is that this mapping is defined in just one place in your software, not so much the auto part.

I have personally found this way of mapping via Tuple to work very well.

Upvotes: 2

Related Questions