我正在将ApplianceViewModel映射到ApplianceDTO。每个Appliance都有一个ActionViewModel集合,它们映射到ActionDTO。我想要做的是配置映射器以忽略其IsPersisted值为False的ActionViewModels。
我的ViewModel类......
public interface IApplianceViewModel : INotifyPropertyChanged
{
ObservableCollection<IActionViewModel> Actions { get; set; }
// other properties removed for simplicity
}
public interface IActionViewModel : INotifyPropertyChanged
{
bool IsPersisted { get; set; }
// other properties removed for simplicity
}
我的DTO课程......
public class ApplianceDTO
{
public IEnumerable<ActionDTO> Actions { get; set; }
// other properties removed for simplicity
}
public class ActionDTO
{
// properties removed for simplicity
}
我设置了这样的映射......
Mapper.CreateMap<IApplianceViewModel, ApplianceDTO>();
Mapper.CreateMap<IActionViewModel, ActionDTO>()
var appliance = new ApplianceViewModel {
Actions = new ObservableCollection<IActionViewModel>(
new List<IActionViewModel> {
new ActionViewModel { IsPersisted = true },
new ActionViewModel { IsPersisted = false }
}};
var applianceDTO = Mapper.Map<IApplianceViewModel, ApplianceDTO>(applianceDTO);
目前我的applianceDTO将在其Actions集合中有两个项目,但我想设置我的映射,以便不映射IsPersisted属性设置为false的ApplianceActionViewModel。我可以这样做吗?
Omu的评论引导我使用ValueResolver来映射动作集合。我对这个解决方案并不满意,但它是最好的选择。
首先我创建了一个自定义ValueResolver。
public class IsPersistedCollectionResolver : ValueResolver<IApplianceViewModel, IEnumerable<ActionDTO>>
{
protected override IEnumerable<ActionDTO> ResolveCore(IApplianceViewModel source)
{
return Mapper.Map<IEnumerable<IActionViewModel>, IEnumerable<ActionDTO>>(source.Actions.Where(x => x.IsPersisted));
}
}
然后我修改了我的代码,以便在映射配置中使用它。
Mapper.CreateMap<IApplianceViewModel, ApplianceDTO>()
.ForMember(dest => dest.Actions, opt => opt.ResolveUsing<IsPersistedCollectionResolver>());
Mapper.CreateMap<IActionViewModel, ActionDTO>();
答案 0 :(得分:0)
Mapper.map(objects.Where(o => o.IsPersisted == true))