automapper many to one mapping

2019-05-19 06:50发布

问题:

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

回答1:

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));


标签: c# AutoMapper