我正在尝试将类型UserProfileEditorViewModel映射到类型UserProfile,如下所示:
public ActionResult Edit(UserProfileEditorViewModel userProfileViewModel)
{
UserProfile user = _getUserByIdQuery.Invoke(SessionData.UserId);
Mapper.Map(userProfileViewModel, user);
当前哪个抛出此错误:
Value supplied is of type System.String but expected
MyNamespace.Web.Models.UserProfileEditorViewModel.
在Mapper.Map(userProfileViewModel,user);行上.
我的映射配置如下:
Mapper.CreateMap<UserProfileEditorViewModel, UserProfile>()
.ForMember(
dto => dto.Tags,
opt => opt.ResolveUsing<TagNameStringToTagCollectionResolver>());
TagNameStringToTagCollectionResolver如下所示:
protected override IEnumerable<Tag> ResolveCore(string source)
{
return _getTagsByNamesQuery.Invoke(source.Split(','));
}
任何想法为什么会引发该异常?我是Automapper的新手,有些困惑.
解决方法:
这里的问题是TagNameStringToTagCollectionResolver需要在其ResolveCore方法上接受UserProfileEditorViewModel类型的参数.
显示的错误消息表明,当映射中某处需要提供UserProfileEditorViewModel类型的值时,它的方法签名中正在提供string类型的值.
给出的措辞有点令人困惑,但这还是我解决问题的方式.
protected override IEnumerable<Tag> ResolveCore(UserProfileEditorViewModel source)
{
return _getTagsByNamesQuery.Invoke(source.Tags.Split(','));
}