使用AutoMapper到对象的属性映射到串 [英] Using AutoMapper to map the property of an object to a string
问题描述
我有以下型号:
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
}
我希望能够使用AutoMapper映射标签的
键入一个字符串属性在我的ViewModels之一。名称
属性
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.
我创建了一个自定义的解析器试图处理这种映射,使用下面的code:
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;
}
}
我使用下面的code映射:
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.
我是什么做错了吗?
推荐答案
这是因为你试图映射到实际的目标类型,而不是目标类型的属性。你可以达到你想要的:
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);
尽管这是一个简单得多只是重写的ToString对标签类。
although it would be a lot simpler just to override ToString on the Tag class.
这篇关于使用AutoMapper到对象的属性映射到串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!