我是否正确使用Automapper 2.0的“包含"功能? [英] Am I using Automapper 2.0's Include functionality correctly?
问题描述
要么我不行,要么不行...我有一个Source类,我想映射到彼此继承的多个视图.
Either I'm not, or it isn't working... I have a single Source class that I want to map to multiple views that inherit from each other.
基本上,基类是Detail,子类是Edit或Update,它们使用与Detail相同的所有数据,另外还有两个字段来管理自己的列表或其他内容.
Basically the base class is the Detail, and the child class is Edit or Update which use all the same data as Detail, plus a couple other fields to manage their own lists or whatever.
这是我正在使用的地图:
Here are the maps I'm using:
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>();
然后,如果我对Mapper.Map(ticket)的任何使用MapFrom的属性都没有求值,那么它们最终将得到在没有设置映射的情况下所拥有的值.
Then if I Mapper.Map(ticket) any of the properties that use MapFrom don't get evaluated, they just end up with the values they'd have had if there was no set mapping.
那这里怎么了?
推荐答案
如果不想两次调用Mapper.Map
,则可以作为替代解决方案.您可以将Detail
的常见映射移到扩展方法中:
As an alternative solution if you don't want to call Mapper.Map
two times. You can move the common mappings of Detail
into an extension method:
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
映射器时使用该扩展方法:
And then use that extension method when registering the Ticket -> Update
and Ticket -> Edit
mappers:
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();
然后您可以正常使用地图:
Then you can use Map normally:
Ticket ticket = new Ticket();
var edit = Mapper.Map<Ticket, Edit>(ticket);
var update = Mapper.Map<Ticket, Update>(ticket);
这篇关于我是否正确使用Automapper 2.0的“包含"功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!