简体   繁体   中英

Mapping multiple objects to one object with AutoMapper

I have 6 properties in C Class and I want to map 3 of my properties from A method with output class A and 3 others from B method with output Class B

First, I map A to C (which is defined at MappingProfile class and 3 other properties are ignored) and then I map B to C (which has been defined like previous one)

My problem is that in the second Map my c object is always going to be override with b object and 3 other properties (which I got them from a object) come back as null (because they don't exist in B class).

In the end, I want to Have all data from a and b objects in my c object.

Mapping operations -

Adaptee Amethod = new Adaptee();
List<A> a = Amethod.A().ToList();
List<B> b = Amethod.B().ToList();
List<C> c1 = _mapper.Map<List<A>, List<C>>(a);
List<C> c = _mapper.Map(b, c1);

Mapping profiles -

public MappingProfile()
{
    CreateMap<A, C>()
        .ForMember(z => z.FN, opt => opt.MapFrom(x => x.FN))
        .ForMember(z => z.LN, opt => opt.MapFrom(x => x.LN))
        .ForMember(z => z.uniqe, opt => opt.MapFrom(x => x.uniqe))
        .ForMember(z => z.Addr, opt => opt.Ignore())
        .ForMember(z => z.HomeTown, opt => opt.Ignore())
        .ForMember(z => z.NID, opt => opt.Ignore());
        
    CreateMap<B, C>()
        .ForMember(z => z.Addr, opt => opt.MapFrom(x => x.Addr))
        .ForMember(z => z.HomeTown, opt => opt.MapFrom(x => x.HomeTown))
        .ForMember(z => z.NID, opt => opt.MapFrom(x => x.NID))
        .ForMember(z => z.FN, opt => opt.Ignore())
        .ForMember(z => z.LN, opt => opt.Ignore())
        .ForMember(z => z.uniqe, opt => opt.Ignore());
}

I'm using AutoMapper.Extensions.Microsoft.DependancyInjection v8.1.0.

you can use this method for multipli Object

services.AddSingleton(provider => new MapperConfiguration(cfg =>
{
    cfg.AddProfile(new sampleProfileMapper());
}).CreateMapper());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM