C# 使用 AutoMapper 将对象的属性映射到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11189729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:56:01  来源:igfitidea点击:

Using AutoMapper to map the property of an object to a string

c#.netmappingautomapperautomapper-2

提问by marcusstarnes

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 Nameproperty of the Tagtype to a string property in one of my viewmodels.

我希望能够使用 AutoMapperNameTag类型的属性映射到我的一个视图模型中的字符串属性。

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?

我究竟做错了什么?

采纳答案by Rob West

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.

尽管仅在 Tag 类上覆盖 ToString 会简单得多。

回答by ZafarYousafi

ForMember means you are providing mapping for a member where you want a mapping between type. Instead, use this :

ForMember 意味着您正在为需要类型之间映射的成员提供映射。相反,使用这个:

Mapper.CreateMap<Tag, String>().ConvertUsing<TagToStringConverter>();

And Converter is

转换器是

public class TagToStringConverter : ITypeConverter<Tag, String>
{
    public string Convert(ResolutionContext context)
    {
        return (context.SourceValue as Tag).Name ?? string.Empty;
    }
}