[英]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). 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.我已经让它与“hack”一起工作,我在其中明确捕获值,然后在
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.我不想使用示例的前四行,而是使用传统的 AutoMapper lambda 表达式将它们包含在内。 Possible?
可能的?
I'd just use mapping to an existing object:我只是使用映射到现有的 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:并在配置中保留
Ignore()
行,但使用AfterMap()
删除那些不再需要的行:
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()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.