对于所有感兴趣的人,我创建了一个 ValueInjecter 扩展,以便将您现有的 AutoMapper 映射配置与 ValueInjecter 一起使用。
我创建了这个扩展是因为我必须切换到 ValueInjecter,因为我无法针对 Client Framework 4.0 编译 AutoMapper。而且我不想重写我的映射配置。
例子:
public class CalendarEvent
{
public DateTime EventDate { 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; }
// Additional Members to show further mapping possibilities
public string BarToIgnore { get; set; }
public bool AlwaysTrue { get; set; }
}
static void Main(string[] args)
{
// You can use the AutoMapper extension for the ValueInjecter like you would user AutoMapper
// Model
var calendarEvent = new CalendarEvent
{
EventDate = new DateTime(2008, 12, 15, 20, 30, 0),
Title = "Company Holiday Party"
};
// Configure AutoMapper
Mapper.CreateMap<CalendarEvent, CalendarEventForm>()
.ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date))
.ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour))
.ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Title))
.ForMember(dest => dest.BarToIgnore, opt => opt.Ignore())
.ForMember(dest => dest.AlwaysTrue, opt => opt.UseValue(true));
Mapper.AssertConfigurationIsValid();
// Perform mapping
CalendarEventForm form = Mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);
// Assertions
Debug.Assert(form.EventDate == new DateTime(2008, 12, 15));
Debug.Assert(form.EventHour == 20);
Debug.Assert(form.EventMinute == 30);
Debug.Assert(form.Title == "Company Holiday Party");
Debug.Assert(form.BarToIgnore == null);
Debug.Assert(form.AlwaysTrue == true);
}
它看起来像 AutoMapper,但在内部它使用 ValueInjecter ;)希望你喜欢这个扩展。
下载:http ://wordpress.ad-factum.de/AutoMapperConfig_UsingValueInjecter.zip