Jamie Dixon
Jamie Dixon

Reputation: 53991

AutoMapper Value supplied is of wrong type

I'm trying to map a type UserProfileEditorViewModel to a type UserProfile as follows:

public ActionResult Edit(UserProfileEditorViewModel userProfileViewModel)
        {
            UserProfile user = _getUserByIdQuery.Invoke(SessionData.UserId);

            Mapper.Map(userProfileViewModel, user);

Which currently throws this error:

Value supplied is of type System.String but expected MyNamespace.Web.Models.UserProfileEditorViewModel.

On the line Mapper.Map(userProfileViewModel, user);.

My mapping configuration for this looks like:

Mapper.CreateMap<UserProfileEditorViewModel, UserProfile>()
                .ForMember(
                   dto => dto.Tags, 
                   opt => opt.ResolveUsing<TagNameStringToTagCollectionResolver>());

where TagNameStringToTagCollectionResolver looks like:

 protected override IEnumerable<Tag> ResolveCore(string source)
        {
            return _getTagsByNamesQuery.Invoke(source.Split(','));
        }

Any ideas why it's throwning that exception? I'm new to Automapper and a bit stumped.

Upvotes: 3

Views: 586

Answers (1)

Jamie Dixon
Jamie Dixon

Reputation: 53991

The issue here is that TagNameStringToTagCollectionResolver needs to accept a parameter of type UserProfileEditorViewModel on its ResolveCore method.

The error message being displayed indicates that something somewhere in the mapping is supplying a value of type string in it's method signature when it needs to be supplying a value of type UserProfileEditorViewModel.

It's a bit of a confusing exception given the wording but this is how I solved the problem non the less.

protected override IEnumerable<Tag> ResolveCore(UserProfileEditorViewModel source)
        {
            return _getTagsByNamesQuery.Invoke(source.Tags.Split(','));
        }

Upvotes: 3

Related Questions