要么我没有,要么它不工作。。。我有一个Source类,我想将它映射到相互继承的多个视图。
基本上,基类是Detail,子类是Edit或Update,它们使用与Detail相同的所有数据,加上其他几个字段来管理自己的列表或其他什么。
以下是我正在使用的地图:
Mapper.CreateMap<Ticket, Detail>()
.Include<Ticket, Update>()
.Include<Ticket, Edit>()
.ForMember(dest => dest.Priority, opt => opt.MapFrom(src => src.Priority.Code))
.ForMember(dest => dest.TicketID, opt => opt.MapFrom(src => src.ID))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.StatusCode))
.ForMember(dest => dest.Category, opt => opt.MapFrom(src => src.ProblemCategoryCode))
.ForMember(dest => dest.crmBusCode, opt => opt.MapFrom(src => src.Company.crmBusCode))
.ForMember(dest => dest.TeamMembers, opt => opt.MapFrom(src => src.Schedules.Where(s => s.CompleteTime == null)));
Mapper.CreateMap<Ticket, Update>()
.ForMember(m => m.Schedules, opt => opt.MapFrom(t => t.Schedules.Where(s => s.EmployeeID == Util.CurrentUserID() && s.CompleteTime == null)));
Mapper.CreateMap<Ticket, Edit>();
然后,如果I Mapper.Map(ticket)使用MapFrom的任何属性都没有得到评估,那么它们最终只会得到如果没有设置映射时会有的值。
那么这里出了什么问题?
如果您不想调用Mapper.Map
两次,则作为替代解决方案。您可以将Detail
的常见映射移动到一个扩展方法中:
public static class MappingExtensions
{
public static IMappingExpression<Ticket, TDest> MapDetailProperties<TDest>(
this IMappingExpression<Ticket, TDest> mapBase) where TDest : Detail
{
return mapBase
.ForMember(dest => dest.Priority,
opt => opt.MapFrom(src => src.Priority.Code))
///....
.ForMember(dest => dest.TeamMembers,
opt => opt.MapFrom(src => src
.Schedules.Where(s => s.CompleteTime == null)));
}
}
然后在注册Ticket -> Update
和Ticket -> Edit
映射器时使用该扩展方法:
Mapper.CreateMap<Ticket, Update>()
.MapDetailProperties()
.ForMember(m => m.Schedules, opt => opt.MapFrom(t => t.Schedules
.Where(s => s.EmployeeID == Util.CurrentUserID() &&
s.CompleteTime == null)));
Mapper.CreateMap<Ticket, Edit>()
.MapDetailProperties();
然后你可以正常使用地图:
Ticket ticket = new Ticket();
var edit = Mapper.Map<Ticket, Edit>(ticket);
var update = Mapper.Map<Ticket, Update>(ticket);
我是否正确使用了Automapper 2.0的Include功能?
否--当使用.Include
时,AutoMapper希望目标类与源类处于类似的层次结构中(此处将对此进行进一步讨论)。换句话说,如果要映射到Ticket
到Detail
、Update
和Edit
的不同子类,则Include
将是合适的。
这对你的情况似乎没有帮助。我建议使用.Map
的重载,它接受一个现有的对象并对其进行修改
Ticket ticket = new Ticket();
Edit edit = new Edit();
Mapper.Map<Ticket, Detail>(ticket, edit);
// Edit has now been automapped using the base mapping.
Mapper.Map<Ticket, Edit>(ticket, edit);
// The properties unique to Edit have now been mapped.