Seriphos
Seriphos

Reputation: 369

How can I accomplish the following mapping with Automapper?

I want to map the class (Entity),

public class Source {
   public int x;
   public string y;
   public bool z;

   public int a;
   public int b;
   public int c;

   //bunch of other fields
   //...
   //..
   //.
}

to the following class (View Model):

public class Destination {
   public MyClass1 A;
   public MyClass2 B;
}

where MyClass1, MyClass2 are defined as follows:

public class MyClass1 {
   public int x;
   public string y;
   public bool z;
}

public class MyClass2 {
   public int a;
   public int b;
   public int c;
}

Is this possible with Automapper?

Upvotes: 2

Views: 179

Answers (2)

gmn
gmn

Reputation: 4319

Just tested this, and it works in isolation...

        Mapper.CreateMap<Source, MyClass1>();
        Mapper.CreateMap<Source, MyClass2>();

        Mapper.CreateMap<Source, Destination>()
            .ForMember(x => x.A, m => m.MapFrom(p => p))
            .ForMember(x => x.B, m => m.MapFrom(p => p));


        var source = new Source() { a = 1, b = 2, c = 3, x = 4, y = "test", z = true };
        var destination = new Destination() { A = new MyClass1(), B = new MyClass2() };
        Mapper.Map<Source, Destination>(source, destination);

Upvotes: 7

tmesser
tmesser

Reputation: 7666

Automapper handles flattening automatically, which seems to be what you're asking for here. It's in the reverse direction from the way it's normally done, though, so it's possible it will choke. If it does, you can handle it using individual .ForMember() mappings.

In your case, it would look something like the following:

Mapper.CreateMap<Source, Destination>()
    .ForMember(cv => cv.Destination, m => m.MapFrom(
    s => new Class1(s.x, s.y, s.z))

I don't have the ability to run this through an environment right this second so please point out any syntactical errors and I'll correct them.

Upvotes: 1

Related Questions