Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

c# - Using AutoMapper to map the property of an object to a string

I have the following model:

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }
}

I want to be able to use AutoMapper to map the Name property of the Tag type to a string property in one of my viewmodels.

I have created a custom resolver to try to handle this mapping, using the following code:

public class TagToStringResolver : ValueResolver<Tag, string>
    {
        protected override string ResolveCore(Tag source)
        {
            return source.Name ?? string.Empty;
        }
    }

I am mapping using the following code:

Mapper.CreateMap<Tag, String>()
    .ForMember(d => d, o => o.ResolveUsing<TagToStringResolver>());

When I run the application I get the error:

Custom configuration for members is only supported for top-level individual members on a type.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because you are trying to map to the actual destination type rather than a property of the destination type. You can achieve what you want with:

Mapper.CreateMap<Tag, string>().ConvertUsing(source => source.Name ?? string.Empty);

although it would be a lot simpler just to override ToString on the Tag class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...