AutoMapper之投影

7.投影

AutoMapper有一种自定义映射,叫投影。接下来我们通过一个示例来了解它

7.1示例

//源对象
public class CalendarEvent
{
	public DateTime Date { get; set; }
	public string Title { get; set; }
}

//目标对象
public class CalendarEventForm
{
	public DateTime EventDate { get; set; }
	public int EventHour { get; set; }
	public int EventMinute { get; set; }
	public string Title { get; set; }
}

映射说明:把日期拆开分别映射到不同字段

CalendarEvent中属性 说明 CalendarEventForm的属性
Date Date中的年月日-> EventDate
Date Date中小时-> EventHour
Date Date中分钟-> EventMinute

[TestClass]
public class Projection
{
    [TestMethod]
    public void ProjectionTest()
    {
        var calendarEvent = new CalendarEvent
        {
            Date = new DateTime(2008, 12, 15, 20, 30, 0),
            Title = "Company Holiday Party"
        };

        // 初始化映射
        Mapper.Initialize(cfg =>
          cfg.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)));
        
        CalendarEventForm form = Mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);

        Assert.AreEqual(new DateTime(2008, 12, 15), form.EventDate); // 通过
        Assert.AreEqual(20, form.EventHour);// 通过
        Assert.AreEqual(30, form.EventMinute);// 通过
        Assert.AreEqual("Company Holiday Party", form.Title);// 通过
    }
}
posted @ 2017-04-04 21:11  山中自有人  阅读(411)  评论(0编辑  收藏  举报