简体   繁体   中英

Keep property of source object to destination property when mapping objects using AutoMapper Map function

I want to map most properties of the current object ( this a FinancialBase instance) to another object (the 'destination' object, the schedule , an instance of a Schedule class). However, I need to keep a small set of the destination's properties.

I've got it working with a 'hack' where I capture the values explicitly then use these in the AfterMap function. See example code.

var id = schedule.Id;
var parentId = schedule.ParentId;
var scheduleNo = schedule.ScheduleNo;
var schName = schedule.SchName;

var config = new MapperConfiguration(
    cfg => cfg.CreateMap<FinancialBase, Schedule>()
    .ForMember(d => d.Id, opt => opt.Ignore())
    .ForMember(d => d.ParentId, opt => opt.Ignore())
    .ForMember(d => d.ScheduleNo, opt => opt.Ignore())
    .ForMember(d => d.SchName, opt => opt.Ignore())
    .AfterMap((s, d) => d.Id = id)
    .AfterMap((s, d) => d.ParentId = parentId)
    .AfterMap((s, d) => d.ScheduleNo = scheduleNo)
    .AfterMap((s, d) => d.SchName = schName));
var mapper = config.CreateMapper();
schedule = mapper.Map<Schedule>(this);

I would prefer not to use the first four lines of my example but instead have them included using a conventional AutoMapper lambda expression. Possible?

I'd just use mapping to an existing object:

var existingSchedule = new Schedule()
{
    Id = 12,
    ParentId = 34,
    ScheduleNo = 56,
    SchName = "Foo",
};

var schedule = mapper.Map(this, existingSchedule);

And in the configuration leave the Ignore() lines but remove those with AfterMap() as they are no longer needed:

var config = new MapperConfiguration(
    cfg => cfg.CreateMap<FinancialBase, Schedule>()
        .ForMember(d => d.Id, opt => opt.Ignore())
        .ForMember(d => d.ParentId, opt => opt.Ignore())
        .ForMember(d => d.ScheduleNo, opt => opt.Ignore())
        .ForMember(d => d.SchName, opt => opt.Ignore()));

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