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

时间:2022-09-17 02:29:15

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.

我希望能够使用AutoMapper将标记类型的名称属性映射到一个视图模型中的字符串属性。

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?

我做错了什么?

2 个解决方案

#1


41  

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.

尽管在标记类上覆盖ToString要简单得多。

#2


9  

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;
    }
}

#1


41  

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.

尽管在标记类上覆盖ToString要简单得多。

#2


9  

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;
    }
}