AutoMapper之投影

谁都会走 提交于 2020-02-06 06:43:34

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);// 通过
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!