例子:
目标class
public class CalendarEvent
{
//事件日期
public DateTime Date { get; set; }
//事件标题
public string Title { get; set; }
}
对应的DTO
public class CalendarEventForm
{
//事件日期
public DateTime EventDate { get; set; }
//时间对应的小时
public int EventHour { get; set; }
//时间对应的分钟
public int EventMinute { get; set; }
//事件标题
public string Title { get; set; }
}
如果是手动映射的形式:
比较复杂,并且每次都需要手动映射
// 定义一个日历事件
var calendarEvent = new CalendarEvent
{
Date = new DateTime(2014, 12, 15, 20, 30, 0),
Title = "公司聚会"
};
CalendarEventForm form = new CalendarEventForm
{
EventDate = calendarEvent.Date.Date,
EventHour = calendarEvent.Date.Hour,
EventMinute = calendarEvent.Date.Minute,
Title = calendarEvent.Title
};
使用自定义的AutoMapper
// 配置Mapping
Mapper.CreateMap<CalendarEvent, CalendarEventForm>()
.ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.Date.Date))
.ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.Date.Hour))
.ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.Date.Minute));
//Mapping
CalendarEventForm form = Mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);
ForMember函数
AutoMapper提供了相关的API来支持自定义的Mapping配置,并且他支持lamda。
IMappingExpression<TSource, TDestination> ForMember(Expression<Func<TDestination, object>> destinationMember
第一个参数是目标属性,第二个参数是一定义的映射Expression, Expression让这个映射变得更加的动态,可以直接使用表达式或者干脆直接来个函数调用:
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => ChangeTitle(src.Title));//调用方法
.ForMember(dest => dest.Title, opt => opt.MapForm(src => src.Title.Where(....);//表达式
string ChangeTitle(string title)
{
//自定义处理
...
return "myName" + title;
}