2

i want to map one type to other but i have multiple properties in the first type that is required to get one property of other type

for example

public class A
{ 
    public int a{get;set;}
    public int b{get;set;}
    public int c{get;set}
}

public class B
{ 
    public C z{get;set;}
    public int c{get;set}
}

public class C
{ 
    public int a{get;set;}
    public int b{get;set;}
    public int Total{get;set}
}

public class D
{
    public C Get(A a)
    {
       var c = new C();
       c.a = a.a;
       c.b= b.a;
       c.c = c.a + c.b;
       return c
    }   
}

here I want to map A to B, so how can i do it using Automapper

Richard
  • 29,854
  • 11
  • 77
  • 120
rajansoft1
  • 1,336
  • 2
  • 18
  • 38

1 Answers1

3

You can use ForMember to map from your simple types to your complex type like this:

AutoMapper.CreateMap<A,B>()
.ForMember(dest => dest.z.a, opt => opt.MapFrom(src => src.a));

You can chain as many of these ForMember invocations as you need.

Another approach would be to configure a map for A to C such that:

AutoMapper.CreateMap<A,C>();

and then in your mapping from A to B you can say:

AutoMapper.CreateMap<A,B>()
.ForMember(dest => dest.z, opt => opt.MapFrom(src => src))

This tells AutoMapper to use the mapping from A to C for member z when doing a mapping from A to B (Since src is an instance of A and dest is an instance of C)

Update

If you need to use your D class' Get method to do your mappings from A to C then you can do so using the ConstructUsing method in AutoMapper.

AutoMapper.CreateMap<A,B>()
.ForMember(dest => dest.z, opt => opt.ConstructUsing(src => new D().Get(src));
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
  • but I need to get C from Get function of D as i dont have z in class A – rajansoft1 Jun 07 '13 at 08:04
  • Why do you need to do that? It is automappers job to deal with mappings. In your example, you're taking the job away from automapper and doing the mapping yourself in in the Get method. That's isn't necessary. – Jamie Dixon Jun 07 '13 at 08:07
  • but I want automapper to use this function and pass object of class A to get c and then map to class B with the calculated value of C, is it possible – rajansoft1 Jun 07 '13 at 08:15